Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  146] [ 4]  / answers: 1 / hits: 19799  / 15 Years ago, sun, november 8, 2009, 12:00:00

Can you explain it in most simple words?



Best with a demo script.


More From » json

 Answers
44

JSON is a way of sharing data (usually between the browser and a server).



JavaScript allows for two way to store collections of values:



//arrays:
[value, value, value]
//objects:
{key:value, key:value, key:value}


At some point, a guru known as Doug realized that it is usually most efficient to send data to JavaScript already setup like an object. [Rather than PHP sending a comma-delimited strings, post-data, XML, or even HTML, all of which have to be painstakingly parsed by the JavaScript].



So he called that idea JSON, wrote up a spec for it, and the standard was born.



For example, let's say your login.php script should return the users name, total posts, and days since registered:



//XML
<xml..><details>
<user>Jim</user><posts>239</posts><since>Jan09</since>
</details>
//POSTData
user=Jim&posts=239&since=Jan09
//JSON
{user:'Jim', posts:239, since:'Jan09'}


The last one can be easily parsed by JS (using eval), and the details can be used intuitively:



var user = details.user;


EDIT:



It was correctly noted that to be valid JSON, all strings must be double quoted.
This was done to prevent JS from croaking on reserved keywords (in JS one may not use certain words, such as class, unless they are quoted. So {class:'mike'} cannot be used).



It should also be pointed out that PHP 5.2+ has functions which can be used to create or parse JSON:



<?php
$arr = array ('a'=>'ay','b'=>'bee','c'=>'cee');
echo json_encode($arr); //outputs {a:ay,b:bee,c:cee}
?>


The json_decode function will ONLY work if the JSON is valid, so it is sometimes important to get those double-quotes right.


[#98362] Wednesday, November 4, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carl

Total Points: 633
Total Questions: 105
Total Answers: 105

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;