JSON (JavaScript Object Notation) is a lightweight data-interchange format.

This post does not cover everything under the sun about JSON but serves as a quick intro to working with JSON in JavaScript.

JSON data is written as comma-delimited key/value pairs. Keys require double quotes and values can be any of:

  • a string
  • a number
  • an object
  • an array
  • a boolean
  • null

Valid JSON values can be any of the above, except:

  • a function
  • a Date object
  • undefined

JSON derives its syntax from Plain JavaScript objects and very little work is required working with JSON in JavaScript.

// normal JavaScript Object
const details = { 
  firstName: "Luke",
  lastName: "Skywalker",
  age: 29,
  hobbies: ['Gaming', 'Hiking'], 
// accessing data in the object
const firstName = details.firstName
console.log(firstName) // prints Luke

Converting to JSON with JSON.stringify

To convert to JSON:

const json = JSON.stringify(details)
console.log(json) // outputs {"firstName":"Luke","lastName":"Skywalker","age":29,"hobbies":["Gaming","Hiking"]}

Try it out in the playground

JSON files

JSON files are saved with .json file extension.

In summary, JSON format is:

  • key/value pairs
  • separated by commas
  • keys are enclosed in double quotes

With JSON, one can

  • Fetch the JSON string
  • Parse the JSON into regular JavaScript objects (or Dicts in Python/Ruby)
  • Use the parsed object as a normal JavaScript object

That’s all. I’m working on the book titled: “A Modern JavaScript Primer”, please share your views here: 👉 What concepts do you find difficult to grasp in JavaScript?