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
Click on the HTML tag which creates an horizontal line in web page.
<br /> <em> <hr />
Some content ...
<hr />
Content under line ...
Which CSS property defines the text color?
font-style font-variant color
h2 {
  color: #cbdafb;
}
Click on the function which searches if a character, or text exists in a string.
indexOf() toString() split()
var str = "Web courses - http://CoursesWeb.net/";
if(str.indexOf("http://") == -1) alert("http:// isn`t in string");
else alert("http:// is in string");
Which function splits a string into an array of strings based on a separator?
array_merge() explode() implode()
$str = "apple,banana,melon,pear";
$arr = explode(",", $str);
var_export($arr);      // array (0=>"apple", 1=>"banana", 2=>"melon", 3=>"pear")
Convert JSON in JavaScript

Last accessed pages

  1. PHP OOP - Accessor and Destructor methods (1706)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (143079)
  3. Web Programming Tests (703)
  4. The Stage, Panels and Tools in Flash (10398)
  5. SHA512 Encrypt hash in JavaScript (24997)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (312)
  2. CSS cursor property - Custom Cursors (36)
  3. The Mastery of Love (35)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (32)
  5. Read Excel file data in PHP - PhpExcelReader (28)