JSON is not a JavaScript Object, jsonjavascript object
A short and concise article, I think it is good to translate.
Original Author: Fizer Khan
Original address http://www.fizerkhan.com/blog/posts/JSON-is-not-Javascript-Object.html
Many people regard JSON as a JavaScript Object, but it is not at all. JSON is just a string representation inspired by the JavaScript Object Structure. JSON is designed to transmit data between servers and browsers. Because of its simplicity, it is also used in applications other than browsers and servers.
I tried to copy some JavaScript objects and send them to the JSON-based bookmarks Web server, but it does not work. Why? Look at the JavaScript Object I want to send.
{ name : "why this kolaveri di", url : "http://www.youtube.com/watch?v=YR12Z8f1Dh8", singer: "Dhanush", movie: "3", music : "Anirudh Ravichandran", views : 10000000, // Adding this for testing purpose play : function() { },}
After sending the message, the slave server returns the following error: "Unexpected token n" (sent using the Express framework of NodeJS), which indicates that the message I sent is not legal JSON. To find the reason, I read the JSON spec written by Douglas Crockford and finally understood:
I changed it to the correct format:
{ "name" : "why this kolaveri di", "url" : "http://www.youtube.com/watch?v=YR12Z8f1Dh8", "singer": "Dhanush", "movie": "3", "views" : 10000000, "music" : "Anirudh Ravichandran"}
I think it is very important to learn JSON notation, because many configuration files (package. json, bower. json) in Web development are in JSON format. Therefore, every Web developer must understand JSON.
Happy coding and Have a nice day.
How does javascript convert an Array object into a json string (not a json object )?
You can try this:
<Script>
Var arr = ["red", "blue", "yellow"]
Var s = obj2str (arr );
Document. write (s );
Function obj2str (obj ){
Var ret = [];
For (var I = 0, len = obj. length; I <len; I ++ ){
Ret. push (obj [I]);
}
Return '[' + ret. join (',') + ']';
}
</Script>
Result output:
[Red, blue, yellow]
How does javascript obtain json objects?
Parse json strings in js and insert html
Var popcity = '{$ popcity }';
Popcity = eval (popcity );
Var list = '';
For (var I = 0; I <popcity. length; I ++ ){
List + = '<option value = "' + popcity [I]. cid + '">' + popcity [I]. name + '</option>'
}
<Tr> <td class = "Tname1"> region: </td> <td class = "Tinfo1"> <select name = "dealcity" class = "dealcity" id = "dealcity"> <option value = ""> '+ infor. city + '</option> <option value = "0"> all </option>' + list + '</select> </td> </tr>
Jquery can parse json, And it is relatively secure,
Var obj = jQuery. parseJSON ('{"name": "John "}');
The above is the method for js to read the json string after receiving the json string. If you have any questions, contact me.