Bootstrap FreeKB - Node.js - Parsing JSON using JSON.parse
Node.js - Parsing JSON using JSON.parse

Updated:   |  Node.js articles

Let's say you have a file named app.js that contains the following.

let data = '{"my_string": "Hello World", "my_boolean": true, "my_integer" :42}';
let obj = JSON.parse(data);
let pretty_json = JSON.stringify(obj, null, 2)
console.log(pretty_json)
console.log(obj.my_string);
console.log(obj.my_boolean);
console.log(obj.my_integer);

 

If you use the node CLI to run app.js, the following should be displayed as stdout on your console.

~]$ node app.js
{"my_string":"Hello World","my_boolean":true,"my_integer":42}
Hello World
true
42

 

In this example, a new key/value pair is appended to the JSON object. The key is "foo" and the value is "bar".

let data = '{"my_string": "Hello World", "my_boolean": true, "my_integer" :42}';
let obj = JSON.parse(data);
obj.foo = 'bar'
let pretty_json = JSON.stringify(obj, null, 2)
console.log(pretty_json)

 

In this example, the values of keys in the JSON object are updated.

let data = '{"my_string": "Hello World", "my_boolean": true, "my_integer" :42}';
let obj = JSON.parse(data);

obj.my_string = 'Goodbye World'
obj.my_boolean = false
obj.my_integer = 67

let pretty_json = JSON.stringify(obj, null, 2)
console.log(pretty_json)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2601ed in the box below so that we can be sure you are a human.