In this lesson you can learn how to convert JSON string to a JavaScript object, and to convert JavaScript objects into a JSON string that can be transfered to different aplications.
JSON.parse()
method.
var obj = JSON.parse(json_string);
Web site: <span id='wurl'></span><br> Title: <span id='wtitle'></span> <script> // example of what is received from server var jsnstr ='{"url": "https://coursesweb.net/", "title": "Web Development Courses", "users": 1500}'; // parse the 'jsnstr', and store the JSON object in 'obj' var obj = JSON.parse(jsnstr); // uses the JavaScript object, adds the values from 'url', and 'title' in web page document.getElementById('wurl').innerHTML = obj.url; document.getElementById('wtitle').innerHTML = obj.title; </script>
JSON.parse()
can be used to parse JSON strings that contains only values which are objects or arrays (with numeric and string type data), if the object contains complex data (methods, functions), the JSON.parse() will return "unexpected keyword" error. In this case, if you are sure that date are safe, use eval()
.
JSON.stringify()
method.
var str = JSON.stringify(object);
JSON.stringify()
method to convert the object into a JSON string, then, to show the results, the string is displayed in a <div> in webpage.
JSON string: <div id='showjson'></div> <script> // object with an arrays and an object var obj = { 'courses': ['html', 'php', 'ajax'], 'site': {'url': 'https://coursesweb.net/', 'title': 'Web Development Courses', 'users': 1500} } // converts the 'obj' into a JSON string var jsonstr = JSON.stringify(obj); // displays the JSON text in the HTML element with id='showjson' document.getElementById('showjson').innerHTML = jsonstr; </script>
The JSON string can be easily converted again to an object (or associative array) in the script on server. For example, in PHP by using json_decode()
.
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net