Javascript JSON Parsing

Javascript JSON Parsing is used to transfer data from client i.e (browser) to server and from server to the client(browser).When client receives data from the server then it will be in JSON string format. To access the receiving, convert it into an object using JSON.parse().

JSON Parse Example

Let us suppose, receiving string data is:

    
  var data = '{"name":"John", "age":30, "city":"New York"}';
   

Please keep in mind that ,here data is JSON object. Let us convert it into javascript object using JSON.parse() method.

    
   var jsObject = JSON.parse(data);
   

Source Code

          
            <script type="text/javascript">
const data = 
'{"name":"Smith", "age":30, "job":"Designer","country":"india"}'
const obj = JSON.parse(data);
document.getElementById("result").innerHTML = obj.name + ", " + obj.job;
</script>          
        
Try it now

JSON Array To Javascript Array

JSON array can be converted into javascript array using JSON.parse().Please keep in mind that the JSON array will be converted into a javascript array rather than a javascript object.

    
var fruits = '["Apple", "Mango", "Orange", "Grape"]';
var jsArray = JSON.parse(fruits);
   

Source Code

          
            <script type="text/javascript">
var fruits = '["Apple", "Mango", "Orange", "Grape"]';
var jsArray = JSON.parse(fruits);
document.getElementById('result').innerHTML = jsArray[0] +","+ jsArray[2];
</script>          
        
Try it now

Parsing Functions

JSON does not allow function but it can be used inside JSON by placing function as a string and then converting it into function.

Source Code

          
            <script type="text/javascript">
var data = 
'{"name":"Smith", "cost":"function () {return 3000;}", "production":"Testing Machines"}';
var jsobj = JSON.parse(data);
jsobj.cost = eval("(" + jsobj.cost + ")");
document.getElementById("result").innerHTML = jsobj.name + ", " + jsobj.cost();
</script>          
        
Try it now

Web Tutorials

Javascript JSON Parsing
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4