JSON (Java Script Object Notation) is an object-based data format. It is a text format, so it is human readable. The syntax is based on programming languages such as C and Java, so it is also fairly easy for computer programs to parse. A JSON string contains a collection of name-value pairs. A collection of name-value pairs is called an object. JSON objects are always enclosed in curly-braces. The name of each pair is always a string. The value can only be one of a few pre-defined types. One of those types is another object, so objects can be nested. Other pre-defined types are arrays, numbers and strings. The following is a minimal JSON example with one object containing only a single name-value pair:
{ “name”: “value” } |
When an object contains multiple name-value pairs, each pair is separated by a comma, as in the following example:
{ “first”: “first value”, “second”: “second value” } |
JSON arrays are always enclosed in square brackets and contain multiple comma-separated values. The type of each value can be any of the types defined by JSON. The following example shows JSON arrays:
{ “numbers”: [0, 1, 2, 3, 4], “names”: [“alice”, “bob”, “sam”] } |
One common use for JSON is to encode and decode objects in JavaScript. Most JavaScript objects can be converted to and from JSON-encoded strings by using the JSON.stringify() and JSON.parse() functions. This converts the object into a form that is suitable for transferring over the internet. After it has been transferred and received, it can be converted back into an object for processing. The following JavaScript code demonstrates this:
class Thing { constructor(s, c) { this.size = s; this.color = c; } }
t1 = new Thing(“small”, “yellow”); s1 = JSON.stringify(t); t2 = JSON.parse(s1); if ((t2.size == “small”) && (t2.color == “yellow”)) { console.log(“OK”); } |