Languages
[Edit]
EN

JavaScript - parse json

6 points
Created by:
Root-ssh
177780

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

Alternative titles

  1. JavaScript - convert json to object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - JSON

Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join