Talking about JSON and JavaScript with example

JSON is almost everywhere in our daily programming work. So

  • What is JSON?
  • What does it have to do with JavaScript?
  • How do we deal with JSON data in JavaScript?

1. JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format. Because it is easy to read, write, and user-friendly to parse and generate, it is smaller, faster, and easier to parse than XML, making it an ideal data exchange language and a text format that is completely language independent.

For example, the following JSON data is used to describe a book:

{
  "name": "i am book",
  "totalpage": 200,
  "chapter": ["chapter1", "chapter2", "chapter3"]
}

Note: JavaScript is not JSON, and JSON is not JavaScript. But JSON has a long pedigree with JavaScript, and JSON’s data format evolved from JavaScript objects. (It can be seen from the name)

2. The difference between JSON and JavaScript

JSON is a data format, which can also be said to be a specification. JSON is used for cross-platform data exchange, independent of language and platform. The JavaScript object is an instance and exists in memory. JavaScript objects cannot be transmitted, they can only be transmitted after being serialized into a JSON string.

In JavaScript, we cannot call the following objects as JSON, such as:

// this is just an JS object
var book = {}

// this is just an JS object too
var book = { name: 'test', page: 500 }

// this is just an JS object too
var book = { 'name': 'test', 'age': 500 }

// JS object in JSON format
var book = { "name": "test", "age": 500 }

// String in JSON format
var book = '{"name":"test","age":500}'

// an array in JSON format
var bookArr = [
  { "name": "test", "age": 500 },
  { "name": "test1", "age": 180 }
]

// String in JSON format
var bookStr = '[{"name":"test","age":500},{"name":"test1","age":180}]'
Although JSON is very similar to the strict literal representation of JavaScript objects, it is wrong to interpret JavaScript object properties with double quotation marks as JSON. It just conforms to the grammatical rules of JSON. JSON and JavaScript objects are essentially two completely different things, just like "Java" and "JavaScript".

In JavaScript, the JSON object contains two methods, JSON.parse() for parsing and JSON.stringify() for conversion. Except for these two methods, the JSON object itself has no other effect, nor can it be called or used as a constructor.

3. JSON.stringify()

Convert a JavaScript object or value to a JSON string.

JSON.stringify(value, replacer, space)
  • value: the value to be serialized into a JSON string.
  • replacer(optional) : Parameter replacer (optional). If the parameter is a function, each attribute of the serialized value will be converted and processed by the function during the serialization process; if the parameter is an array, only contained in The property names in this array will be serialized into the final JSON string; if the parameter is not provided (or the value is null), all the properties of the object will be serialized.
const people = {
  name: 'test',
  page: 20
}

const peopleStr1 = JSON.stringify(people, ['name'])
const peopleStr2 = JSON.stringify(people, (key, value) => {
  if (typeof value === 'string') {
    return undefined
  }
  return value
})

console.log(peopleStr1) // '{"name":"test"}'
console.log(peopleStr2) // '{"page":500}'
  • space (optional): The parameter space (optional), specifies a blank string for indentation, used to beautify the output (pretty-print). If the parameter is a number, it indicates how many spaces there are. When the value is greater than 10, the output space is 10, and if it is less than 1, it means there are no spaces. If the parameter is a string, the string will be treated as a space. If the parameter is not provided (or the value is null), there will be no spaces. Note that if you use a non-empty string as a parameter value, it cannot be parsed by JSON.parse() and a SyntaxError will be thrown.

4. JSON.parse()

The JSON.parse() method is used to parse JSON strings and construct JavaScript values or objects described by the strings. An optional reviver function is provided to perform transformation (operation) on the resulting object before returning.

JSON.parse(text, reviver)
  • text: a string to be parsed into a JavaScript value.
  • reviver(optional): the converter, if the function is passed in, can be used to modify the original value generated by the analysis, and the call time is before the parse function returns.

5. others

For the processing of Line separator and Paragraph separator, you can see here: JSON.stringify

RSS