python json解析出现No JSON object could be decoded的报错

import requests
import re
import json

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }

错误信息:Traceback (most recent call last):
File "D:/Python/JetBrains PyCharm 5.0.4/PyCharm 5.0.4/Myproject/test1/", line 10, in
File "D:\Python\lib\", line 339, in loads
return _default_decoder.decode(s)
File "D:\Python\lib\json\", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\Python\lib\json\", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded



你得到的content先看看是什么数据 看上去不是json数据

Could not write JSON: java.lang.Integer cannot be cast to java.math.BigInteger


答案就在这里:Could not write JSON: java.lang.Integer cannot be cast to java.math.BigInteger

Csdn user default icon
python错误:ValueError: No JSON object could be decoded

#-*- coding:utf-8 -*- import requests from operator import itemgetter # 执行API调用并存储响应 url = '' r = requests.get(url) print("Status code:", r.status_code) # 处理有关每篇文章的信息 submission_ids = r.json() submission_dicts = [] for submission_id in submission_ids[:30]: # 对于每篇文章,都执行一个API调用 url = ('' + str(submission_id) + '.json') submission_r = requesets.get(url) print(submisssion_r.status_code) reponse_dict = submission_r.json() submission_dict = { 'title': resopnse_dict['title'], 'link': '' + str(submission_id), 'comments': response_dict.get('descendants', 0) } submission_dicts.append(submission_dict) submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), recerse=Ture) for submission_dict in submission_dicts: print("/nTitle:", submission_dict['title']) print("Discussion link:", submission_dict['link']) print("Comeents", submission_dict['comments'])


有这样一个菜单json文件: {"id":"100" "name":"File" "parent":"#", "id":"200" "name":"Edit" "parent":"#", "id":"300" "name":"Search" "parent":"#", "id":"400" "name":"Project" "parent":"#", "id":"500" "name":"Help" "parent":"#", "id":"101" "name":"New" "parent":"100", "id":"102" "name":"Open" "parent":"100", "id":"103" "name":"Load" "parent":"100", "id":"201" "name":"Cut" "parent":"200", "id":"202" "name":"Copy" "parent":"200", "id":"203" "name":"Paste" "parent":"200", "id":"301" "name":"Back" "parent":"300", "id":"302" "name":"Replace" "parent":"300", "id":"303" "name":"Jump" "parent":"300", "id":"401" "name":"Add" "parent":"400", "id":"402" "name":"Remove" "parent":"400", "id":"403" "name":"Close" "parent":"400", "id":"501" "name":"Mode" "parent":"500", "id":"502" "name":"Key" "parent":"500", "id":"503" "name":"About" "parent":"500", "id":"1011" "name":"xx" "parent":"101", "id":"2011" "name":"yy" "parent":"201", "id":"3011" "name":"zz" "parent":"301", } 想要打印出如下结果: 100 File 100 File 101 New 100>101 File>New 1011 xx 100>101>1011 File>New>xx 102 Open 100>102 File>Open 103 Load 100>103 File>Load 200 Edit 200 Edit 201 Cut 200>201 Edit>Cut 2011 yy 200>201>2011 Edit>Cut>yy 202 Copy 200>202 Edit>Copy 203 Paste 200>203 Edit>Paste 300 Search 300 Search 301 Back 300>301 Search>Back 3011 zz 300>301>3011 Search>Back>zz 302 Replace 300>302 Search>Replace 303 Jump 300>303 Search>Jump 400 Project 400 Project 401 Add 400>401 Project>Add 402 Remove 400>402 Project>Remove 403 Close 400>403 Project>Close 500 Help 500 Help 501 Mode 500>501 Help>Mode 502 Key 500>502 Help>Key 503 About 500>503 Help>About 想要得出如下结果: 属性Parent如果为#时,说明这是一个根节点,直接打印,打印格式为 ID+Name+ID+Name 属性Parent如果非#时,则需要找到父节点的ID和Name,打印格式为 ID+Name+Parent ID>ID+Parent Name>Name 如果父节点也不是一个根节点,打印格式为 ID+Name+根节点ID>Parent ID>ID+根节点Name>Parent Name>Name,以此类推。当菜单层级非常多时,此处判断如何写一个递归算法,逐级找到某节点的所有父节点。


<div class="post-text" itemprop="text"> <p>My Python script:</p> <pre><code>import requests import json location = '' port = 8000 # Setup the REST API URL string apiString = 'http://' + location + ':' + str(port) + '/edsa-Python/Matrix_mult_dynamic/run_python.php' print apiString #Make the REST API Request resp = requests.get(apiString) print resp.text # print resp.encoding # Get the JSON that is returned if resp.status_code == the_json = resp.json() #print the_json </code></pre> <p>Error: I get an error saying that No JSON object could be decoded. Below is the error that I get when I run the python script in the command prompt:</p> <pre><code> Traceback (most recent call last): File "", line 25, in &lt;module&gt; the_json = resp.json() File "C:\Python27\lib\site-packages equests-2.12.0-py2.7.egg equests\", line 841, in json return complexjson.loads(self.text, **kwargs) File "C:\Python27\lib\json\", line 339, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded </code></pre> </div>


![如图返回值]( $jsoninfo = json_decode($result); $errcode = $jsoninfo -> errcode; //正常 $errmsg = $jsoninfo -> errmsg; //正常 $card = $jsoninfo -> card; $cardid = $card -> card_id; //null $cardid应该怎么取啊,取出来为空,上面的操作不行,求助各位!

python BeautifulSoup模块解码

在IDLE中执行下面的代码出现警告 代码: soup = BeautifulSoup('utf-8','ignore'), "html") 警告是: WARNING:root:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER. 官方解释是: In rare cases (usually when a UTF-8 document contains text written in a completely different encoding), the only way to get Unicode may be to replace some characters with the special Unicode character “REPLACEMENT CHARACTER” (U+FFFD, �). If Unicode, Dammit needs to do this, it will set the .contains_replacement_characters attribute to True on the UnicodeDammit or BeautifulSoup object. This lets you know that the Unicode representation is not an exact representation of the original–some data was lost. If a document contains �, but .contains_replacement_characters is False, you’ll know that the � was there originally (as it is in this paragraph) and doesn’t stand in for missing data. 我该怎么办呢?


<div class="post-text" itemprop="text"> <p>my question may be the duplicate of many questions but i have tried all my options but couldn't get to parse the json that i receive via an Ajax request </p> <p>hi,</p> <p>so im getting this json response as a result of Ajax call</p> <pre><code>{ "audi": [ "100", "200", "80", "90", "a3", "a4", "a6", "a8" ] } </code></pre> <p>this is the json i am receiving following is my one of the attempted options</p> <pre><code>var obj = JSON.parse(html); alert("json decoded"); for(var yahoo in obj) { alert(obj[yahoo]); // this line gives me 100,200,80,90,... } </code></pre> <p>any help is much appreciated ...</p> <p>EDIT:</p> <p>here is my ajax call</p> <pre><code> $.ajax({ url: "makemodel.php", type: "POST", data: {data:data}, cache: false, async:false, dataType:'json', success: function (html) { alert("success"); var obj = JSON.parse(html); alert("json decoded"); for(var yahoo in obj) { alert(obj[yahoo]); } }//ajax success ends });//ajax ends </code></pre> </div>


![图片说明](![图片说明]( ![图片说明]( 求大佬帮忙!


<div class="post-text" itemprop="text"> <p>I am passing data to an ajax call that has been 'json_stringified'. I am able to pass the data to PHP, however when trying to access the items within the passed array, I receive the following error:</p> <p>'Trying to get property of non-object'</p> <p>I've tried several things, but I am stuck. Can someone please assist? My code is below:</p> <p>js:</p> <pre><code> $.ajax({ url: 'http://localhost/VibeSetter/services/getlocationsFavs.php', dataType: 'json', type: "POST", data: {favs: JSON.stringify(localStorage.getArray("myFavs"))}, success: function(data, status) { $.each(data, function(i,item) { //pass to function to fill array populateLocationsArray(i+1, item.idlocations,,item.longitude, item.latitude); }); }, error: function(jqXHR, textStatus, errorThrown) { console.log(arguments); // alert('HTTP Error: '+errorThrown+' | Error Message:'+textStatus); } }); </code></pre> <p>}</p> <p>console.log(localStorage.getArray("myFavs")) returns: </p> <p>{locations: 1},{locations: 0},{locations: 4293315}</p> <p>php:</p> <pre><code>&lt;?php header('Content-type: application/json'); include 'config.php'; $data = json_decode($_POST['favs']); var_dump($data); foreach($data as $d) { print $d-&gt;locations; } ?&gt; </code></pre> <p>which returns the following in chrome developer tools pane:</p> <pre><code>array(3) { [0]=&gt; string(14) "{locations: 1}" [1]=&gt; string(14) "{locations: 0}" [2]=&gt; string(20) "{locations: 4293315}" } </code></pre> <p><br> <b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php</b> on line <b>10</b><br> <br> <b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php</b> on line <b>10</b><br> <br> <b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\VibeSetter\services\getlocationsFavs.php</b> on line <b>10</b><br></p> <p>Can someone please tell me how to access each element of this array? The idea is to parse each 'location' value and concatenate the locations in a query further in the code as specific values in a query search.</p> <p>Thanks in advance</p> </div>


<div class="post-text" itemprop="text"> <p>I am trying to send a JSON object containing username and password info from an iOS app to my server for login. However, it seems like the php code never received the JSON object or decoded it correctly. I have tried many different ways to convert JSON object and send to server, but none of them succeeded. I am coding in swift 2 by the way. Any help? THANKS!</p> <p>Here is my swift code:</p> <pre><code>let myUrl = NSURL(string: "myURL"); let request = NSMutableURLRequest(URL: myUrl!); request.HTTPMethod = "POST"; let params : [String : AnyObject] = ["username": username!, "password": password!]; request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type"); do { let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions()); request.HTTPBody = jsonData; let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String print(jsonString); print(request.HTTPBody); } catch { print(error) } let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -&gt; Void in do{ let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary print(response) if let parseJSON = json { let resultValue = parseJSON["type"] as? Int print("result: \(resultValue)") } } catch { print(error) } }) task.resume() </code></pre> <p>And here is my php code:</p> <pre><code>require("Conn.php"); require("MySQLDao.php"); $fp = fopen("data.txt", "a+"); $data = file_get_contents('php://input'); $json = json_decode($data, false); $username = $_POST['username']; $password = $_POST['password']; fwrite($fp, $data); fwrite($fp, $json); fwrite($fp, $username); fwrite($fp, $password); fclose($fp); $returnValue = array(); if (empty($username) || empty($password)) { $returnValue["status"] = "error"; $returnValue["message"] = "Missing required field"; echo json_encode($returnValue); return; } $dao = new MySQLDao(); $dao-&gt;openConnection(); $userType = $dao-&gt;passwordAuthentification($username, $password); if ($userType != null) { $returnValue["type"] = (int)$userType; echo json_encode($returnValue); } else { $returnValue["type"] = -1; $returnValue["message"] = "user is not found"; echo json_encode($returnValue); } $dao-&gt;closeConnection(); </code></pre> </div>


<div class="post-text" itemprop="text"> <p>My code in iOS:</p> <pre><code>NSString * some_str = @"{\"one\":\"two\",\"three\":\"four\"}"; NSData *objectData = [some_str dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&amp;error]; AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFHTTPRequestSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [manager POST:@"" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"Error: %@", error); }]; </code></pre> <p>My code in backend (PHP):</p> <pre><code>&lt;?php if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){ throw new Exception('Request method must be POST!'); } $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : ''; if(strcasecmp($contentType, 'application/json') != 0){ throw new Exception('Content type must be: application/json'); } //Receive the RAW post data. $content = trim(file_get_contents("php://input")); $decoded = json_decode($content, true); echo $content; // $responses = array(); header("Content-type: application/json, charset=utf-8"); // echo json_encode($responses); $conn-&gt;close(); ?&gt; </code></pre> <p>If I echo $content, the response received by iOS will be some hex number. i.e. 3c21444f 43545950 (hex number for the json string start from the tail to the head connected by a "&amp;" sign, i.e. three=four&amp;one=two). If I echo $decoded, it returns an empty json.</p> <p>And if I try to decode the json received by Post request, it failed. I believed that the received object was a possible input for json_decode function.</p> <p>Should I rewrite my iOS code or PHP code or both?</p> </div>


<div class="post-text" itemprop="text"> <p>i am useing an API getting some json objects.</p> <p>The one i need is: results_html</p> <p>When you look at the name you see it will be html. My problem is, in the json it is unicode encoded. When i try to decode it some characters are wrong!</p> <p>I tried out JSON_UNESCAPED_UNICODE and i tried out some str_replace() things like this:</p> <pre><code>$json_object = str_replace('\u2122', 'e2 84 a2;', str_replace('\u2605', 'e2 98 85', file_get_contents($url))); $json_decoded = json_decode($json_object); </code></pre> <p>But i didnt get any good result! Sometimes the total json crashes or the chars are bad anyway.</p> <p><b>EDIT:</b> Here is an example: WHen i use:</p> <pre><code>$json_object = file_get_contents($url); $json_decoded = json_decode($json_object); $html = $json_decoded -&gt; results_html; </code></pre> <p>the $html will echo this in an utf8 encoded html body: â StatTrakâ¢</p> <p>Does somebody have any idea?</p> <p>Thank You so far.</p> </div>


<div class="post-text" itemprop="text"> <pre><code>{ "api_response": "{\"LeadRefNumber\":\"23223222433534543554\",\"ApplicationNumber\":\"2323343434234234\",\"StatusCode\":\"3456\",\"ProcessingStatus\":\"111\",\"CreditLimit\":\"5454554\",\"Messages\":{\"Message\":\"test.\"}}" } </code></pre> <p>NOTE: The above is the json encoded one, but couldn't access it as array even if the json is decoded with json_decode().</p> </div>

解析json_decoded php数组的最佳方法

<div class="post-text" itemprop="text"> <p>what would be the best way to parse stringified one dimensional array?</p> <p>input array</p> <pre><code>$inputArray = array( "id" =&gt; "foo", "name" =&gt; "bar", "money[0][amount]" =&gt; 30, "money[0][countryCode]" =&gt; "US", "money[1][amount]" =&gt; 25, "money[1][countryCode]" =&gt; "CA", ) </code></pre> <p>desired output array </p> <pre><code>$outputArray = array( "id" =&gt; "foo", "name" =&gt; "bar", "money" =&gt; array( [0] =&gt; array( "amount" =&gt; 30, "countryCode" =&gt; "US" ), [1] =&gt; array( "amount" =&gt; 25, "countryCode" =&gt; "CA" ), ), ) </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I have json which is not decoded to struct. </p> <p>I know that error somewhere in my code, but I'm stuck and do not know where the error is and what am I doing wrong</p> <p>Help me please, here is my code:</p> <pre><code>type GOOGLE_JSON struct { code string `json:"code"` clientId string `json:"clientId"` redirectUri string `json:"redirectUri"` } body := []byte(`{"code":"111","clientId":"222","redirectUri":"333"}`) //google_json := GOOGLE_JSON{} var google_json GOOGLE_JSON err := json.Unmarshal(body, &amp;google_json) if err != nil { fmt.Println(err) } fmt.Println(google_json) </code></pre> <p><a href="" rel="nofollow">example here</a></p> </div>


<div class="post-text" itemprop="text"> <p>I am accessing API for "ConnectWise". the data comes into JSON format. i was able to parse the data into table via PHP. however, empty fields in JSON results in <strong>Undefined index</strong>. This happens for some items with no website, or address for example. the rest shows up fine. Any help or input would be appreciated. </p> <p>Here is my code to get the data from Connectwise: </p> <pre><code>function get_companies(){ $curl = curl_init(); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($curl, CURLOPT_URL, "https://api-"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($curl, CURLOPT_HTTPHEADER, array( "Authorization: Basic (OUR KEY)", 'Content-type: application/json' )); $result = curl_exec($curl); curl_close($curl); $decoded = json_decode($result,true); return $decoded; } </code></pre> <p>And to display the data:</p> <pre><code>function list_all_accounts(){ $accounts = get_companies(); if ( !empty ($accounts)){ foreach ($accounts as $account) { { echo " &lt;/td&gt; &lt;td&gt; $account[id] &lt;/td&gt; &lt;td&gt; $account[name] &lt;/td&gt; &lt;td&gt; $account[addressLine1] &lt;/td&gt; &lt;td&gt; $account[phoneNumber] &lt;/td&gt; &lt;td&gt; $account[website] &lt;/td&gt; &lt;td&gt; $account[name] &lt;/td&gt; &lt;/tr&gt;"; } } } } </code></pre> <p>Update - Json Sample</p> <pre><code> [ { "id": 250, "identifier": "company name ", "name": "company name", "status": { "id": 1, "name": "Active", "_info": { "status_href": "" } }, "type": { "id": 1, "name": "Client", "_info": { "type_href": "" } }, "addressLine1": "address line 1", "city": "New York", "state": "NY", "zip": "11111", "country": { "id": 1, "name": "United States", "_info": { "country_href": "" } }, "phoneNumber": "123456789", "faxNumber": "", "website": "", "territoryId": 2, "accountNumber": "", "dateAcquired": "2006-06-21T04:00:00Z", "sicCode": { "id": 1209, "name": "consulting" }, "annualRevenue": 0, "timeZone": { "id": 1, "name": "GMT-5/Eastern Time: US &amp; Canada", "_info": { "timeZoneSetup_href": "" } }, "leadFlag": false, "unsubscribeFlag": false, "userDefinedField5": "1", "taxCode": { "id": 8, "name": "Tax-State", "_info": { "taxCode_href": "" } }, "billingTerms": { "id": 1, "name": "Net 30 days" }, "billToCompany": { "id": 250, "identifier": "comp1 ", "name": "company1.", "_info": { "company_href": "" } }, "billingSite": { "id": 1291, "name": "company1", "_info": { "site_href": "" } }, "invoiceDeliveryMethod": { "id": 1, "name": "Mail" }, "deletedFlag": false, "mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211", "currency": { "id": 7, "symbol": "$", "isoCode": "USD", "name": "US Dollars", "_info": { "currency_href": "" } }, "_info": { "lastUpdated": "2018-04-02T16:36:05Z", "updatedBy": "user1", "dateEntered": "2006-06-21T16:04:59Z", } }, { "id": 250, "identifier": "company name ", "name": "company name", "status": { "id": 1, "name": "Active", "_info": { "status_href": "" } }, "type": { "id": 1, "name": "Client", "_info": { "type_href": "" } }, "addressLine1": "address line 1", "city": "New York", "state": "NY", "zip": "11111", "country": { "id": 1, "name": "United States", "_info": { "country_href": "" } }, "phoneNumber": "123456789", "faxNumber": "", "website": "", "territoryId": 2, "accountNumber": "", "dateAcquired": "2006-06-21T04:00:00Z", "sicCode": { "id": 1209, "name": "consulting" }, "annualRevenue": 0, "timeZone": { "id": 1, "name": "GMT-5/Eastern Time: US &amp; Canada", "_info": { "timeZoneSetup_href": "" } }, "leadFlag": false, "unsubscribeFlag": false, "userDefinedField5": "1", "taxCode": { "id": 8, "name": "Tax-State", "_info": { "taxCode_href": "" } }, "billingTerms": { "id": 1, "name": "Net 30 days" }, "billToCompany": { "id": 250, "identifier": "comp1 ", "name": "company1.", "_info": { "company_href": "" } }, "billingSite": { "id": 1291, "name": "company1", "_info": { "site_href": "" } }, "invoiceDeliveryMethod": { "id": 1, "name": "Mail" }, "deletedFlag": false, "mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211", "currency": { "id": 7, "symbol": "$", "isoCode": "USD", "name": "US Dollars", "_info": { "currency_href": "" } }, "_info": { "lastUpdated": "2018-04-02T16:36:05Z", "updatedBy": "user1", "dateEntered": "2006-06-21T16:04:59Z", "enteredBy": "CONVERSION", } } ] </code></pre> </div>

json_encode如何获取原始数组[stdClass Object]

<div class="post-text" itemprop="text"> <p>Hello I have this json:</p> <pre><code> [{"org_src":"img\/base\/logo.png","src":"\/cache\/300-logo.png"}, {"org_src":"\/img\/l2.JPG","src":"\/cache\/6l-2.JPG"}, {"org_src":"\/img\/studio\/desk.JPG","src":"\/cache\/desk.JPG"}, ... </code></pre> <p>How looks the array before its is decoded? If I use Json_encode to this, I will get this:</p> <pre><code> Array ( [0] =&gt; stdClass Object ( [og_src] =&gt; img/base/logo.png [src] =&gt; /cache/300-logo.png ) [1] =&gt; stdClass Object ( [og_src] =&gt; /img/l2.JPG [src] =&gt; /cache/6l-2.JPG )... </code></pre> <p>What is stdClass Object? Thanks for any help in advance.</p> <p>with json_decode($test,true); I will get this:</p> <pre><code>Array ( [0] =&gt; Array ( [og_src] =&gt; img/base/logo.png [src] =&gt; /cache/logo.png ) [1] =&gt; Array ( [og_src] =&gt; /img/studio/l2.JPG [src] =&gt; /cache/6l-2.JPG ... </code></pre> <p>This do not help me to see how the origin array looks like.</p> <p>Here is the answer. That what I looked for. Thanks for any suggestion.</p> <pre><code>$stack[0][org_src]= "Hallo"; $stack[0][src] = "scrkjh"; $stack[1][org_src] = "Halfgfglo"; $stack[1][src] = "scrkjh"; json_encode($stack); </code></pre> </div>

python3.x 实现dubbo接口RPC协议自动化测试运行报错:argument should be integer or bytes-like object, not 'str'

``` #!/usr/bin/env python # -*- coding: utf-8 -*- import json import socket import telnetlib class dubbo: # 定义私有属性 __init = False __encoding = "utf8" __finish = 'dubbo>' __connect_timeout = 10 __read_timeout = 10 # 定义构造方法 def __init__(self, host, port): = host self.port = port if host is not None and port is not None: self.__init = True def set_finish(self, finish): ''' defualt is ``dubbo>`` ''' self.__finish = finish def set_encoding(self, encoding): ''' If ``result retured by dubbo`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ''' self.__encoding = encoding def set_connect_timeout(self, timeout): ''' Defines a timeout for establishing a connection with a dubbo server. It should be noted that this timeout cannot usually exceed 75 seconds. defualt is ``10`` ''' self.__connect_timeout = timeout def set_read_timeout(self, timeout): ''' Defines a timeout for reading a response expected from the dubbo server. defualt is ``10`` ''' self.__read_timeout = timeout def do(self, command): # 连接Telnet服务器 try: tn = telnetlib.Telnet(, port=self.port, timeout=self.__connect_timeout) except socket.error as err: print("[host:%s port:%s] %s" % (, self.port, err)) return # 触发doubble提示符 tn.write(b'\n') # 执行命令 tn.read_until(self.__finish.encode(), timeout=self.__read_timeout) # tn.write('%s\n' % command) tn.write(command.encode() + b"\n") # 获取结果 data = '' while data.find(self.__finish) == -1: data = tn.read_very_eager() data = data.split("\n") data = json.loads(data[0], encoding=self.__encoding) tn.close() # tn.write('exit\n') return data def invoke(self, interface, method, param): cmd = "%s %s.%s(%s)" % ('invoke', interface, method, param) return def connect(host, port): return dubbo(host, port) if __name__ == '__main__': Host = '' # Doubble服务器IP Port = 20884 # Doubble服务端口 # 初始化dubbo对象 conn = dubbo(Host, Port) # 设置telnet连接超时时间 conn.set_connect_timeout(10) # 设置dubbo服务返回响应的编码 conn.set_encoding('utf-8') interface = '' method = 'checkCourseStatusByCourseIds' param = '{"courseIds": "9765", "userId": "56645"}' print(conn.invoke(interface, method, param)) command = 'invoke{"courseIds": "9765", "userId": "56645"})' print( ``` ``` #coding=utf8 import sys from kazoo.client import KazooClient import urllib import urllib3 import json import telnetlib import socket import dubbo_telnet Host = '' # zookeeper的地址 def coondoubble_data(servhost, servport,interface,method,param): try: # 初始化dubbo对象 conn = dubbo_telnet.connect(servhost, servport) # 设置telnet连接超时时间 conn.set_connect_timeout(10) # 设置dubbo服务返回响应的编码 conn.set_encoding('utf-8') # print("interface:" + interface, "method:" + method, "param:" + param) data = conn.invoke(interface, method, param) return data except Exception as e: raise e def get_dubbo_full(): global Host zk = KazooClient(hosts="{}".format(Host)) zk.start() urls = [] list = zk.get_children("dubbo") for i in list: if 'serv' in i: #关键字过滤 # print i try: gg = zk.get_children("/dubbo/{}/providers".format(i)) if gg: for j in gg: url = urllib.parse.unquote(j) if url.startswith('dubbo:'): urls.append(url.split('?')[0].split('dubbo://')[1]) except Exception as e: print(e) print(i) services = {} for i in urls: try: path, service = i.split('/') if not services.get(path): services.update({path: []}) services[path].append(service) except Exception as e: pass print(json.dumps(services, indent=4)) def get_dubbo(servername): global Host zk = KazooClient(hosts="{}".format(Host)) zk.start() urls = [] lists = zk.get_children("dubbo") for i in lists: if servername in i: try: # 获取服务发布方 gg = zk.get_children("/dubbo/{}/providers".format(i)) if gg: for j in gg: url = urllib.parse.unquote(j) if url.startswith('dubbo:'): urls.append(url.split('dubbo://')[1]) except Exception as e: print(e) paths=[] for i in urls: try: path, temp = i.split('/') service_name = temp.split('?')[0] method_name = temp.split('methods=')[1].split('&')[0].split(',') paths.append(path) except Exception as e: print(e) services = {"service_name": service_name, "paths": paths, "method_name": method_name} print(services) return services print(json.dumps(services, indent=4)) if __name__ == '__main__': #使用方法get_dubbo('<服务名>') result = get_dubbo("") rs = result["paths"][0] print(rs) servhost, servport = rs.split(':') servport = int(servport) interface = "" method = "getListenCourseAccess" param = '{"382","2157306"}' #get_dubbo('') #param='''{"batSubmitId":null, "logonId":"8ybbmd01.c.0200", "len":"20", "groupId":"020090006110982", "start":"0", "logonLevel":"3", "limitSum1":"40000", "limitSum":"90000000000000000", "endTime":"20200101", "beginTime":"20190101", "batFileName":null, "channelFlag":"1"}''' # #使用方法coondoubble_data('服务提供者ip','服务提供者port','服务名','调用方法','发送数据') # #'服务提供者ip','服务提供者port','服务名','调用方法'从get_dubbo()返回结果中获取 resp = coondoubble_data(servhost, servport, interface, method, param) print(resp) ```


<div class="post-text" itemprop="text"> <p>I apologize for the newbie question, but I'm trying I'm trying to iterate through JSON data without listing the specific objects within.</p> <p>I'm specifying the JSON data first</p> <pre><code>$data = '{ "question":[{ "gender":"Both", "category":"Finance", "question_title":"Will the German Economy Collapse", "country":"Lebanon" }] }'; </code></pre> <p>I'm then decoding $data</p> <pre><code>$jsonDecoded = json_decode($data); </code></pre> <p>I'm then trying to iterate through the decoded JSON variable:</p> <pre><code>foreach ($jsonDecoded-&gt;question as $object){ print $object; } </code></pre> <p>But I'm getting the following error:</p> <pre><code>Catchable fatal error: Object of class stdClass could not be converted to string </code></pre> <p>Any pointers as to where I'm going wrong? Thank you.</p> </div>

如果将值为null的字符串编码的json int解组,则使用null之前的值

<div class="post-text" itemprop="text"> <p>I am trying to unmarshal json that contains ints encoded as strings. Using tags to specify that the field is encoded as a string works, but I am running into issues when the field is null. The main problem, it seems, is that the null is not encoded as a string so the parser ignores it and keeps going. The problem is that it jams in the previously decoded value for some reason.</p> <p>Any ideas on how I can get this parsing correctly?</p> <p>I have the following code:</p> <pre><code>package main import ( "encoding/json" "log" ) type Product struct { Price int `json:",string,omitempty"` } func main() { data := ` [ {"price": "1"}, {"price": null}, {"price": "2"} ] ` var products []Product if err := json.Unmarshal([]byte(data), &amp;products); err != nil { log.Printf("%#v", err) } log.Printf("%#v", products) } </code></pre> <p>Output:</p> <pre><code>[]main.Product{main.Product{Price:1}, main.Product{Price:1}, main.Product{Price:2}} </code></pre> <p><a href="" rel="nofollow">Code on go playground</a></p> </div>


大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...


今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...


文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...



技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Linux 会成为主流桌面操作系统吗?

整理 |屠敏出品 | CSDN(ID:CSDNnews)2020 年 1 月 14 日,微软正式停止了 Windows 7 系统的扩展支持,这意味着服役十年的 Windows 7,属于...


loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...








提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...




关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...






私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

冒泡排序动画(基于python pygame实现)

本项目效果初始截图如下 动画见本人b站投稿: 本项目对应github地址: python版本:3.6,pygame版本:1.9.3。(python版本一致应该就没什么问题) 样例gif如下 ======================= 大爽歌作,mad


Redis核心原理与应用实践 在很多场景下都会使用Redis,但是到了深层次的时候就了解的不是那么深刻,以至于在面试的时候经常会遇到卡壳的现象,学习知识要做到系统和深入,不要把Redis想象的过于复杂,和Mysql一样,是个读取数据的软件。 有一个理解是Redis是key value缓存服务器,更多的优点在于对value的操作更加丰富。 安装 yum install redis #yum安装 b...

现代的 “Hello, World”,可不仅仅是几行代码而已

作者 |Charles R. Martin译者 | 弯月,责编 | 夕颜头图 |付费下载自视觉中国出品 | CSDN(ID:CSDNnews)新手...


即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...


如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...


阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...


不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...




虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...




本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...