# JSON

  • JSON is an abbreviation for JavaScript Object Notation
  • It is mainly used for:
    • data exchange between servers and (web) application, as an alternative to XML
    • describe configuration files in web and other projects e.g: package.json, .prettierrs, .eslint.json, ...
  • Unlike objects, in JSON double quotes are always required, both for the key and for the value e.g: "name": "John"
  • JSON cannot contain functions/methods
  • Only the following values are used in JSON: "key" : <value>
    • numbers: 3.1415927
    • strings: "this is a string"
    • booleans: true and false
    • null: null
    • objects: { "key" : <value> , ... }
    • arrays: [ <value> , ... ]
  • JSON is not only used in JavaScript, but also in Python, Java, ...
  • At this time, JSON it's the most used data exchange format between servers (API's) end clients
  • According to Stack Overflow (opens new window), more questions are now asked about JSON than about other data interchange formats
    Treands stackoverflow

# Converting to and from JSON

methode description
JSON.stringify(obj) convert an object to a JSON string
JSON.stringify({obj}) convert an object to JSON string, nested under the obj key
JSON.parse(<string>) convert a JSON string to an object
  • Some converting examples:
  • Object literal
const user = {
    // properties
    name: 'John',
    surname: 'Doe',
    age: 41,
    // functions (or methodes)
    greet() {
        console.log(`Hi, ${this.name} ${this.surname}`);
    },
};
Copied!
1
2
3
4
5
6
7
8
9
10
  • JSON.stringify(user)
{
    "name": "John",
    "surname": "Doe",
    "age": 41
}
Copied!
1
2
3
4
5
  • JSON.stringify({user})
{
  "user": {
    "name": "John",
    "surname": "Doe",
    "age": 41
  }
}
Copied!
1
2
3
4
5
6
7

# References

Last Updated: 9/25/2021, 8:02:10 AM