JSON Jumpstart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
 * In JSON, curly brackets mark a new object ({ or })
 * Any variable inside the object — also known as the object's attribute — is
 * accessible using the dot syntax (object.attribute) or the bracket syntax
 * (object['attribute']).
 * Open your browser's DevTools console (F12 in any modern browser) to see
 * the output from console.log.
 */


// =========================
// JSON Object
// =========================
var var1 = {
    'var1_1':'value1_1',
    'var1_2':'value1_2'
};
console.log(var1);
// The line above will output> Object { var1_1="value1_1", var1_2="value1_2"}
console.log(var1.var1_1);
// The line above will output> value1_1
console.log(var1['var1_1']);
// The line above will output> value1_1

// =========================
// JSON Array
// =========================
// In JSON, square brackets mark an array ([ or ])
// Any array element is accessible by using a square bracket followed by an index (0,1,2,...)
var var2 = ['value2_1', 'value2_2'];
console.log(var2);
// The line above will output> ["value2_1", "value2_2"]
console.log(var2[0]);
// The line above will output> value2_1

var var3 = [{
        'var3_1':'value3_1',
        'var3_2':'value3_2'
    },{
        'var3_3':'value3_3',
        'var3_4':'value3_4'
    }];
console.log(var3);
// The line above will output> [Object { var3_1="value3_1", var3_2="value3_2"}, Object { var3_3="value3_3", var3_4="value3_4"}]
console.log(var3[0].var3_1);
// The line above will output> value3_1

A few useful additions.

JS objects vs. JSON — they look the same, but they aren’t. The examples above are JavaScript object literals, not strictly JSON. They render and behave the same way at the console, which is why the line between them blurs in tutorials, but there are real differences worth knowing:

  • JSON requires double-quoted string keys: “var1_1”, not ‘var1_1’.
  • JSON values can only be: string, number, boolean, null, object, or array. No undefined, no functions, no Date objects (they get serialized as strings).
  • JSON has no comments and no trailing commas.

If you write what looks like JSON in a .json file but use single quotes, your tool will reject it as invalid. The JS engine accepts both because it’s evaluating JavaScript syntax, not parsing JSON.

The actual JSON API. When you receive JSON from a network request and need to turn it into something you can manipulate — and vice versa — use the two builtins:

1
2
3
4
5
6
7
8
9
10
11
12
13
// JSON string -> JS object
var fromServer = '{"name":"Alice","age":30,"tags":["admin","user"]}';
var obj = JSON.parse(fromServer);
console.log(obj.name);   // "Alice"
console.log(obj.tags[0]); // "admin"

// JS object -> JSON string
var payload = { name: 'Bob', age: 25 };
var body = JSON.stringify(payload);
console.log(body);  // '{"name":"Bob","age":25}'

// Pretty-print with 2-space indent (handy for debugging)
console.log(JSON.stringify(payload, null, 2));

Reaching into deeply nested data. Modern JavaScript gives you a couple of nicer ways to dig into nested objects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var response = {
  user: {
    profile: { name: 'Alice', address: null }
  }
};

// Old way — verbose, and crashes if any link is missing
var name = response.user.profile.name;

// Optional chaining (?.) — returns undefined instead of throwing
// when an intermediate value is null/undefined
var city = response.user?.profile?.address?.city;  // undefined, no error

// Destructuring — pull multiple fields out at once
var { name, profile: { address } } = response.user;

Optional chaining (?.) is especially useful when consuming JSON from an API where some fields are optional — you avoid a tower of if (foo && foo.bar && foo.bar.baz) guards.

Validating JSON. If you’re not sure whether a string is valid JSON, wrap the parse in try/catch — JSON.parse throws a SyntaxError on malformed input:

1
2
3
4
5
6
7
8
function safeParse(str) {
  try {
    return JSON.parse(str);
  } catch (e) {
    console.warn('Not valid JSON:', e.message);
    return null;
  }
}

For one-off command-line validation, the jq tool (or just python3 -m json.tool) will tell you exactly where the error is in the input — much friendlier than the parser’s line/column number.

This entry was posted in javascript, Web Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 9 = thirteen