JSON

Page section: posts
More on JSON

From the JS Crash Course at 36 mins.

JSON (JavaScript Object Notation) is used to send and receive data to a server.

JSON is very similar to a JS list of objects. The difference in syntax is that JSON has double quotes around keys and string values whereas JS does not.

JavaScript can only be used in a browser or with Node JS whereas JSON can be used with many other languages.

Another important difference is that while JavaScript objects can contain functions JSON cannot.

const todos = [
    {
        id: 1,
        text: 'Take out rubbish',
        isCompleted: true
    },
    {
        id: 2,
        text: 'Meet with boss',
        isCompleted: true
    },
    {
        id: 3,
        text: 'Dental appointment',
        isCompleted: false
    }
]

Convert to JSON. First remove const todo = then run through a JS to JSON converter

[
  {
    "id":1,
    "text":"Take out rubbish",
    "isCompleted":true
  },
  {
    "id":2,
    "text":"Meet with boss",
    "isCompleted":true
  },
  {
    "id":3,
    "text":"Dental appointment",
    "isCompleted":false
  }
]

Converting

You can convert JavaScript to JSON with JavaScript. If you have an array called todos:

const todosJSON = JSON.stringify(todos);
console.log(todosJSON);