JSON Syntax and Structure

  • 1

JSON (JavaScript Object Notation) is a language-independent text format. It's a text representation of data using a subset of javascript object syntax and it is used to pass data between systems. JSON is self-describing, meaning it doesn't require external context to describe its structure and content.

The JSON.stringify() and JSON.parse() methods can convert and parse a js object into a JSON object string. A JSON object is a string that conforms to the JSON syntax, representing a data structure.

//We need quotation marks on JSON key/value pairs 
//We can edit and access it like a js object
let notazione = {
  "primo": "nome",
  "secondo": 15
}
console.log( notazione.secondo )    // 15
console.log( notazione["secondo"] ) // 15

notazione.secondo = 22
console.log( notazione["secondo"] )  //22

let stringa = JSON.stringify(notazione) //"{"primo":"nome","secondo":15}"
JSON.parse(stringa)		        //{primo:"nome",secondo:15}
chevron-rightDifferences between JSON and XMLhashtag

XML is a markup language also used to store and transport data. Like JSON, it's self-describing, and can be parsed using XMLHttpRequest. However, unlike JSON, it requires tags, is generally slower, and can't natively transport arrays. It requires data to be wrapped between tags in its XML data, whereas with JSON, we can simply parse it.

//Rendering an object with JSON and XML
let object = {"employees":[
  { "firstName":"John", "lastName":"Doe" },
  { "firstName":"Anna", "lastName":"Smith" },
  { "firstName":"Peter", "lastName":"Jones" }
]}

<employees>
  <employee>
    <firstName>John</firstName> <lastName>Doe</lastName>
  </employee>
  <employee>
    <firstName>Anna</firstName> <lastName>Smith</lastName>
  </employee>
  <employee>
    <firstName>Peter</firstName> <lastName>Jones</lastName>
  </employee>
</employees>

According to the JSON rules, no functions can be passed in a JSON object, and objects like Date() need to be converted to strings before being serialized to JSON.

The JSON.parse() method includes the reviver argument, a function that is called for each key-value pair in the parsed JSON, allowing you to transform the parsed data before it is returned as a JavaScript object.

1

Last updated