How to parse JSON in JavaScript

7 months ago codedestine 0

How to parse JSON in JavaScript :- 

If you had worked on angularJS or any other modern java script framework, then you would have noticed that, now days restful web services are used to communicate ( Getting data or Posting data ) with the server. In restful web services, JSON format is used ( mostly ) as a data-interchange format. So to use it in java script, we first have to parse it and convert it, to an object. JSON stands for JavaScript Object Notation, it is language independent, easy to understand, lightweight data-interchange format.How to parse JSON in JavaScriptLet’s see how to parse JSON in JavaScript :- 

Sample JSON

JSON for book type :-

{
   "id": "01",
   "language": "Java",
   "edition": "third",
   "author": [ "Herbert", "Json", "Andrew" ],
   "chapters": {
                 "Chapter-1": "Introduction",
                 "Chapter-2": "OOP's Concept"
               }
} 

Example :-

<script>

var json = '{"id": "01","language": "Java","edition": "third","author": ["Herbert", "Json", "Andrew"],"chapters": {"Chapter-1": "Introduction","Chapter-2": "OOP's Concept"}}'; 
var jsonObject = JSON.parse(json);

alert(jsonObject["id"]);
alert(jsonObject.id); // 01

alert(jsonObject.chapters.Chapter-1);
alert(jsonObject["chapters"].Chapter-1); // Introduction

alert(json.author[0]; // Herbert

</script>

You may also like :- 

  1. How to read and write JSON in Java using org.json
  2. How to parse JSON in Java using fasterXML / jackson-databind lib

References :- 

  1. JSON.parse() Docs

That’s all for how to parse JSON in JavaScript, If you liked it, please share your thoughts in comments section and share it with others too.