Languages
[Edit]
EN

JavaScript - parse json

6 points
Created by:
Root-ssh
69140

In this short article we would like to show how to convert JSON to object in JavaScript.

The article is focsed on JSON.parse() method, but at the beginning we try to present basic definitions in simple way.

Note: scroll to below exmple if you know well definitions.

Simple definitions:

TermDescription

JSON

Approach to preset JavaScript object as text (can be stored as string type in JavaScript VM).

So:

  • when we create some object in source code using var object = { ... } we can call¬†{ ... } part as JSON - it will be converted automatically to object after program is run / compiled.
    We can say: object was created using JavaScript Object Notation,
  • when we do fetch(...) / AJAX request and we recive response¬†with¬†Content-Type:¬†application/json.
    We can say:  we recived JSON that should be parsed to object.
  • when we store¬†{ ... } in text file or send as message we can call it JSON.
objectStored in memory data strucure.
JSON to string conversion

Operation that deserilises / converts text to object.

We can do it in few ways:

  • with JSON.parse('{}') method that parses JSON to object,
  • with built-in parse method in fetch(...) result:
    var object = fetchResult.json()
    Method json() returns object created from JSON.
  • setting json value for responseType property during using¬†XMLHttpRequest¬†/ XHR¬†that makes¬†response conversion to object.

Quick solution:

// ONLINE-RUNNER:browser;

var json = '{"id": 2, "name": "Tom", "age": 25}';
var object = JSON.parse(json);

console.log(object);         // [object Object]

console.log(object.id);      // 2
console.log(object.name);    // Tom
console.log(object.age);     // 25

console.log(object.address); // undefined
Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join