JS Adventures — Twitter

JSON — Basics

JSON is a data format, not a programming language. Also, JSON shares JavaScript syntax but it is not part of JavaScript and can be used with other programming languages.

JSON represents structured data — just imagine a spreadsheet.

JSON Syntax

  • Simple Values — string, numbers, Booleans, null.
//JSON likes strings in double quotes - rule.
"Hello world!"
  • Objects — key-value pairs.
//JSON also likes quotes around property(key) names - rule.
{
"name": "Luke",
"age": 12
}
  • Array — ordered list of values accessible by index [0, 1, 2…]
//JavaScript
var values = [12, 'howdy', true];
//JSON
[12, "howdy", true]
//JSON : Arrays & objects
{
"title": "JS Adventures",
"authors": [
"Luke DeLux",
"Jose Perez"
]
,
edition: 1,
year: 2016
}

The good browsers support JSON parsing under a native global called JSON. The bad browsers are happy with JSON shim or something similar.


Data Manipulation

Let’s take the most of our data.

stringify() — convert JSON data into string without white spaces.

var jsonData = JSON.stringify(dataRef);

parse() — transform a JSON string into usable JavaScript data.

var jsReady = JSON.parse(jsonData);

JSON.stringify()

This methods accepts three arguments: ObjectData, Filter and Indent.

  1. ObjectData — data to convert.
  2. Filter — can be array or function.
  3. Indent — insert newlines into the data output for easy reading, optional.
JSON.stringify(objectName, function/array/null, 4);

JSON.parse()

Transform the data into Javascript object and it accepts a function as argument, which is mostly used for turning date strings into Date objects. If the data passed is not valid JSON through an error.

var bookCopy = JSON.parse(data, function(key, value){
if (key == "releaseDate"){
return new Date(value);
} else {
return value;
}
});

toJSON()

This method customise JSON data.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.