JavaScript

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is a text format for storing and transporting data. JSON is "self-describing" and easy to understand.

Why use JSON?

When to use ist?

You use JSON if you have some data you want to keep, have data validering, data from users og want to transport data between different programming languages or from one site to a another.

JSON datatypes

The datatypes is

{ 
"name": "Rikke",
"age": 24
}

JSON is built on two structures.
A collection of name/value pairs or an ordered list of values.

The first element is called name and is a string, therefore it needs to have " " around the it. followed by :

The second element is called value and can be a string, number, object, array or boolean value

{ 
"adresse": {
"Street": "Haveneparken 1",
"zipOrPostalCode": 6000,
"city": "Kolding",
"County": "Danmark"
}
}
{ 
"teachers": {
"firstName": "Rikke Domino",
"lastName": "Isaksen",
"topics":["HTML", "CSS", "JavaScript", "WordPress"
}
}
{ 
"employee": {
"skills": ["Carpentry", "Math", "Writing"],
"name" : "Peter",
"age" : 38,
"available": true,
"availableForEmployment": null
}
}

JSON and JavaScript

The JSON format is text only, which means that JSON data can easily be sent between computers, and used by any programming language.
BUT JavaScript can't read JSON, without we are parsing the tekst, so JavaSCript can understand it.

JSON parse

JSON.parse(text)

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string

const json = '{"result":true, "count":42}'; 
const obj = JSON.parse(json);
console.log(obj.count); // expected output: 42
console.log(obj.result);// expected output: true

JSON stringify

JSON.stringify(value)

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

const objectValue = { x: 5, y: 6 }; 
const obj = JSON.stringify(objectValue);
console.log(obj);