JSON (JavaScript Object Notation) is a lightweight data interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. Let’s start JSON Cheat Sheet.
Data Types
number | var myNum = 123.456; | Series of numbers; decimals ok; double-precision floating-point format |
string | var myString = “abcdef”; | Series of characters (letters, numbers, or symbols); double-quoted UTF-8 with backslash escaping |
boolean | var myBool = true; | true or false |
array | var myArray = [ “a”, “b”, “c”, “d” ]; | sequence of comma-separated values (any data type); enclosed in square brackets |
object | var myObject = { “id”: 7 }; | unordered collection of comma-separated key/value pairs; enclosed in curly braces; properties (keys) are distinct strings |
null | var myNull = null; | variable with null (empty) value |
undefined | var myUndefined; | variable with no value assigne |
Objects
var myObject = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "male",
"salary": 70000,
"registered": true
};Access object properties
myObject.sex | returns “male” |
myObject[”age”] | returns 39 |
myObject[0] | returns “John” |
myObject.something | returns undefined |
myObject[6] | returns undefined |
Array of objects
var myArray = [
{
"first": "John",
"last": "Doe",
"age": 39,
"sex": "male",
"salary": 70000,
"registered": true
},
{
"first": "Jane",
"last": "Smith",
"age": 42,
"sex": "female",
"salary": 80000,
"registered": true
},
{
"first": "Amy",
"last": "Burnquist",
"age": 29,
"sex": "female",
"salary": 60000,
"registered": false
}
];Access array elements
myArray[0] | returns { “first”: “John”, “last”: “Doe” … } |
myArray[1] | returns { “first”: “Jane”, “last”: “Smith” … } |
myArray[1].first | returns “Jane” |
myArray[1][2] | returns 42 |
myArray[2].registered | returns false |
myArray[3] | returns undefined |
myArray[3].sex | error: “cannot read property…” |
Arrays
var myArray = [
"John",
"Doe",
39,
"M",
70000,
true
];Access array elements
myArray[1] | returns “Doe” |
myArray[5] | returns true |
myArray[6] | returns undefined |
Nested objects and arrays
var myObject = {
"ref": {
"first": 0,
"last": 1,
"age": 2,
"sex": 3,
"salary": 4,
"registered": 5
},
"jdoe1": [
"John",
"Doe",
39,
"male",
70000,
true
],
"jsmith1": [
"Jane",
"Smith",
42,
"female",
80000,
true
]
};Access nested elements
myObject.ref.first | returns 0 |
myObject.jdoe1 | returns [ “John”, “Doe”, 39 … ] |
myObject[2] | returns [ “Jane”, “Smith”, 42 … ] |
myObject.jsmith1[3] | returns “female” |
myObject[1][5] | returns true |
myObject.jdoe1[myObject.ref.last] | returns “Doe” |
myObject.jsmith1[myObject.ref.age] | returns 42 |
