Problems encountered: Node. js JSON parsing error, syntax error unexpect end of input
Test code
// Test the/statuses/public_timeline interface. Personal applications that are not reviewed will be restricted. SDK example key
Var json_sans_eval = require ('./json_sans_eval ');
Var http = require ('http ');
Var options = {
Host: 'api .weibo.com ',
Port: 80,
Path: '/statuses/public_timeline.json? Source = 1306060637 & count = 2 ',
};
Http. get (options, function (res ){
Res. on ('data', function (chunk ){
Data = JSON. parse ("" + chunk );
Console. log ('body: '+ data. statuses [0]. user. id)
});
}). On ('error', function (e ){
Console. log ("Got error:" + e. message );
});
Use the public key of the weibo nodejs sdk for access, and print the body to be correct. However, an error occurred while parsing chunk as json data.
The JSON global object is encapsulated in nodejs and implemented in the v8 engine at http://code.google.com/p/v8/source/browse/trunk/src/json.js.
Method 1: Verify the http://jsonlint.com/result online is in the correct json format,
Method 2: run the script using git bash to prevent the impact of the cmd GBK encoding environment. The result is still error.
Method 3: Save the text as a json file and analyze it using fs
var fs=require('fs');
var data = fs.readFileSync('package.json', 'utf8')
console.log(JSON.parse(data).statuses[0].user)
You can also get the correct result without specifying the encoding.
Method 4: Use the nodejs demo to start the server and client. The server sends the simple json format data and copies the complicated weibo json data. The result is incorrect.
Try to remove a json data attribute, use nodejs server to send data, and then the client parses and prints the attribute, which is feasible. Some character encoding Problems
Search for encoding problems:
Eval ("(" + chunk + ")"); failed to convert mode to string, error
JSON. parse (chunk) has invalid characters,
JSON. stringify (chunk) cannot parse JSON data after converting the object to string
Download json_sans_eval.js from http://www.openjs.com/scripts/data/json_encode.php/According to http://www.json.org description and import the module,
Server startup:
Var http = require ('http ');
Var weibostring = '{"statuses": [{"created_at": "Tue Feb 28 16:22:06 + 0800 2012", "id": 3418080363744574, "mid": "3418080363744574 ", "idstr": "3418080363744574", "text": "Be sure to HOLD it! Be sure to give @ zhixiang "Popularity + 1" every day. I have a high morale for The Star Medal! Come and help me add popularity to TA! # I want TA's micro Star Medal # campaign link: http://t.cn/zO2ORjf "," source ": "<a href = \" http://q.weibo.com/\ "rel = \" nofollow \ "> Sina micro group </a>", "favorited": false, "truncated": false, "representation": "", "in_reply_to_user_id": "", "in_reply_to_screen_name": "", "thumbnail_pic": "http://ww1.sinaimg.cn/thumbnail/99c886d1jw1dqi27uys16j.jpg", "bmiddle_pic": "http://ww1.sinaimg.cn/bmiddle/99c886d1jw1dqi27uys16j.jpg ", "original_pic": "http://ww1.sinaimg.cn/large/99c886d1jw1dqi27uys16j.jpg", "geo": null, "user": {"id": 2580055761, "idstr": "2580055761", "screen_name ": "Dry dry gold customers", "name": "Dry dry gold customers", "province": "44", "city": "16", "location ": "Guangdong Heyuan", "description": "", "url": "", "profile_image_url": "http://tp2.sinaimg.cn/2580055761/50/0/1", "profile_url": "u/2580055761 ", "domain": "", "weihao": "", "gender": "m", "followers_count": 0, "friends_count": 27, "statuses_count": 1, "favourites_count": 0, "created_at": "Sat Jan 14 00:00:00 + 0800 2012", "following": false, "allow_all_act_msg": false, "geo_enabled": true, "verified": false, "verified_type":-1, "allow_all_comment": true, "avatar_large": "http://tp2.sinaimg.cn/2580055761/180/0/1", "verified_reason": "", "follow_me": false, "online_status": 1, "bi_followers_count": 0, "lang": "zh-cn"}, "reposts_count": 0, "comments_count": 0, "mlevel ": 0, "visible": {"type": 0, "list_id": 0}], "hasvisible": false, "previus_cursor": 0, "next_cursor": 0, "total_number": 1 }'
Http. createServer (function (request, response ){
Response. writeHead (200, {'content-type': 'application/json '});
Response. end (weibostring );
}). Listen (80 );
Console. log ('server running at http: // 127.0.0.1: 80 /');
Client:
var json_sans_eval = require('./json_sans_eval');
var http = require('http');
var options = {
host: 'localhost',
port: 80,
path: '/'
};
http.get(options, function(res) {
res.on('data', function (chunk) {
data = json_sans_eval.jsonParse(""+chunk);
console.log('BODY: ' + data.statuses[0].user.id)
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Finally available, but only the local server is available (parsing syntax error occurs when json2.js is used), but still error is reported when api.weibo.com is used
Try to get data. statuses [0]. source found the problem source content is truncated to <a href = instead of <a href = \ "http://q.weibo.com/\" rel = \ "nofollow \"> Sina micro group </a>
It is considered that js cannot distinguish between "and \" when reorganizing json objects from strings.
It is no problem to obtain and load the dictionary object using python.
import httplib, urllib
import json
conn = httplib.HTTPConnection("api.weibo.com")
conn.request("GET", "/statuses/public_timeline.json?source=1306060637&count=2")
response = conn.getresponse()
data = response.read()
data = json.loads(data)
print data['statuses'][0]['source']
conn.close()
The nodejs sdk only provides sample code output from the interface and does not parse it into a json object again. The format code only uses the JSON. parse method.
Finally accidentally glanced at the unclosed window http://ued.sina.com /? P = 801. I found my own problem. I should not process it in the data event of response (the data may be being sent), but parse it in the end event.
var body = '';
res.on('data', function (chunk) {
body += chunk
});
res.on('end',function(){
weibo = JSON.parse(body)
console.log(weibo.statuses[0].source)
})
Node-weibo, provided by fengmk2)
Source: https://github.com/fengmk2/node-weibo
This netizen is a python enthusiast, ORZ!
Through this very low-level error, I have a better understanding of the node. js event model and read the json learning materials.
Json-related websites:
Old: http://www.json.org/
Json in javascript: http://www.json.org/js.html
Mastering JSON (JavaScript Object Notation): http://www.hunlock.com/blogs/Mastering_JSON_ (_ JavaScript_Object_Notation _)