Learning about JSON

Learning about JSON

JSON JavaScript Object Notation is a lightweight format that is used for data interchanging. All modern browsers support JSON object. JSON objects are surrounded by curly brackets {} and its objects are written in key/value pairs where keys must be string data type and values must be one of the valid JSON data type such as string, number, object, array, boolean, null. Key and values are separated by semicolon.


     "firstName": "JBC",
     "lastName": "Edge",
     "address": {
         "streetAddress": "43 2nd Street",
         "city": "New Zealand",
         "state": "NZ",
         "postalCode": 00064
     "phoneNumbers": [

Used to create a JSON string out of an object or array, it serializes a JavaScript object into a JSON string. It turns a Javascript object into JSON text and stores that JSON text in a string. In simple terms is to create a JSON string out of an object or array.

Used for parsing data that was received as JSON, it deserializes a JSON string into a JavaScript object. Simply it turns a string of JSON text into a JavaScript object

In javascript JSON is a string. Not all Javascripts objects are JSON and vice versa.

var x = {x:y} 

This is Javascript object and NOT JSON

var x = '{"x":"y"}';

This is JSON and NOT Javascrpt object
To convert JSON string into Javascript object you need JSON.parse() function

var x = JSON.parse('{"x":"y"}');


const myObj = {
  name: 'Test',
  age: 2,
  city: 'nandi'

const myObjStr = JSON.stringify(myObj);

// "{"name":"Test","age":2,"city":"nandi"}"

// Object {name: "Test", age: 2, city: "nandi"}

var myObject = JSON.parse(myObjStr);


With Arrays

const myArr = ['carrot', 'spinach', 'tomatoes'];

//JSON string
const myArrStr = JSON.stringify(myArr);

// "["carrot","spinach","tomatoes"]"
//JavaScript object
// ["carrot","spinach","tomatoes"]

var myObject = JSON.parse(myArrStr);


With Second Argument
Can pass second argument as a reviver function to transform object values before they are returned.

const user = {
  name: 'JBC',
  email: 'jbc@jbcedge.com',

const userStr = JSON.stringify(user);

JSON.parse(userStr, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase();
  return value;

Can take two additional arguments first one as replacer function and second as string or number value to use as the returned string.
Replacer function can be used as filtered-out values

const user = {
  id: 12,
  name: 'JBC',
  email: 'jbcedge@jbcedge.com'

function replacer(key, value) {
  console.log(typeof value);
  if (key === 'email') {
    return undefined;
  return value;

const userStr = JSON.stringify(user, replacer);

Adding more characters/strings

const userStr1 = JSON.stringify(user, null, '=>');


Read more here