Javascript Course


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.


Convert JSON string to JavaScript object

One of the most common use of JSON is to fetch JSON data from a web server, as a string that can be converted to JavaScript object to be used in web page.
To convert a JSON string to a JavaScript object, you can use the JSON.parse() method.
var obj = JSON.parse(json_string);

In the following example, the "jsnstr" variable contains a string with a JSON object (The string can be fetched with Ajax, for example from a PHP script, or from a file on server).
- Values from the JSON string are added in HTML elements in webpage.
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().


Convert JavaScript object to JSON string

To convert JavaScript object to JSON string you can use the JSON.stringify() method.
var str = JSON.stringify(object);

This is necessary especially in Ajax applications, when you want to transfer data from JavaScript to a script on server.
- In the next example it is created a JavaScript object containing an array, and another object. We use the 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().

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
Convert JSON in JavaScript

Last accessed pages

  1. Get Lower, Higher, and Closest Number (5342)
  2. Simple Admin Login PHP Script (10894)
  3. jQuery parent, children and nth-child() (13826)
  4. Display UL bullets and OL numbers on the right side (8088)
  5. Convert BBCode to HTML and HTML to BBCode with JavaScript (9298)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (201)
  2. Read Excel file data in PHP - PhpExcelReader (66)
  3. The Mastery of Love (56)
  4. PHP Unzipper - Extract Zip, Rar Archives (51)
  5. Working with MySQL Database (34)
Chat
Chat or leave a message for the other users
Full screenInchide