let myObj, myJSON, text, obj;
// Storing data:
myObj = { name: "John", age: 31, city: "New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name + ' is ' + obj.age;
x
variable (but it's not ideal way of sending JSON to a server)var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
JSON.parse(str)
will not convert date string to date object and we get an errorlet str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str);
document.write( meetup.date.getDate() ); // Error!
The value of meetup.date
is a string, not a Date
object.
That is why JSON.parse
was unable to transform that string into a Date
object.
...
Passing the reviving function to JSON.parse
as the second argument fixes the issue.
The reviving function returns all values “as is”, but date
will become a Date
object and the error will not occur
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( meetup.date.getDate() ); // now works!
replacer
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
// All the properties (except occupiedBy) are the encoded
document.write( JSON.stringify(meetup, function replacer(key, value) {
return (key == 'occupiedBy') ? undefined : value;
}));
The function will be called for every (key, value)
pair and should return the replaced
value, which will be used instead of the original one. Or undefined
if the value is to be skipped.
...
In our case, we can return value
“as is” for everything except occupiedBy
. To ignore occupiedBy
, the code above returns undefined
.
The result of the code above will be the following:{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
As we expected all the values are encoded except occupiedBy
JSON.stringify
is used with the first argument only.
But if we need to fine-tune the replacement process, like to filter out circular references
, we can use the second argument of JSON.stringify
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants']) );
If we pass an array of properties to it, only these properties will be encoded, so the result will be:{"title":"Conference","participants":[{},{}]}
As the result shows, the property list is applied to the whole object structure. So the objects in participants
are empty, because name
is not in the list.
Let’s include in the list every property except room.occupiedBy
that would cause the circular reference:let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
The result will be:{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
Now everything except occupiedBy
is serialized. But the list of properties is quite long.
Fortunately, we can use a function instead of an array as the replacer
.JSON.stringify(value, replacer, space)
is the number of spaces to use for pretty formattinglet user = {
name: "John",
age: 25,
roles: {
isAdmin: false,
isEditor: true
}
};
document.write('<pre>' + JSON.stringify(user, null, 8) + '</pre>');
It’s fine if we want to send an object over a network.
The space
argument is used exclusively for a nice output.
Note: max value of space parameter is 20
The result of the above code:{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}
It has 8 spaces for each TABnull
when we want to JSON.stringify the JavaScript objectdocument.write(JSON.stringify({ x: 5, y: 6 }) + "<br />");
// expected output: "{"x":5,"y":6}"
document.write(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]) + "<br />");
// expected output: "[3,"false",false]"
document.write(JSON.stringify({ x: [10, undefined, function(){}, Symbol('d'), new Date(2006, 0, 2, 15, 4, 5)] }) + "<br />");
// expected output: "{"x":[10,null,null,null,"2006-01-02T11:04:05.000Z"]}"
toString
methodlet user = {
name: "John",
age: 30,
toString() {
return `{name1: "${this.name}", age1: ${this.age}}`;
}
};
document.write(user);
// document.write(JSON.stringify(user));
The code above will produce the following result:{name1: "John", age1: 30}
let room = {
number: 23,
toJSON() {
return this.number;
}
};
let meetup = {
title: "Conference",
room
};
// document.write(JSON.stringify(room));
document.write(JSON.stringify(meetup));
Result of the code above is the following{"title":"Conference","room":23}
$schema
- The $schema keyword states that this schema is written according to the draft v4 specification
title
- the title of the schema
description
- the description of the schema
type
- defines the type of the JSON (object / array)
properties
- defines various keys and their value types, minimum and maximum values to be used in JSON file
required
- this keeps a list of required properties
minimum
- minimum acceptable value for the item
exclusiveMinimum
- If "exclusiveMinimum" is present and has boolean value true, the value must be greater than the value of "minimum"
maximum
- maximum acceptable value for the item
exclusiveMaximum
- If "exclusiveMaximum" is present and has boolean value true, the value must be lower than the value of "maximum"
multipleOf
- a numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer
maxLength
- the length of a string instance is defined as the maximum number of its characters
minLength
- the length of a string instance is defined as the minimum number of its characters
pattern
- a string instance is considered valid if the regular expression matches the instance successfully
...
JSON schema example{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string",
"minLength": 5,
"maxLength": 20
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": [
"id",
"name",
"price"
]
}
JSON that the schema above belongs to:{
"id": 2,
"name": "Lorem ipsum dolor si",
"price": 0.5
}
If the JSON was:{
"id": 2.5,
"name": "Lorem ipsum dolor sit amet",
"price": -0.5
}
It would have the following errors:- Invalid type. Expected Integer but got Number
- String 'Lorem ipsum dolor sit amet' exceeds maximum length of 20
- Float -0.5 is less than minimum value of 0
For validating the JSON with its schema, the resource below can be usedhttps://www.jsonschemavalidator.net/