Navigating JSON

Photo by Steve Johnson on Unsplash

Introduction

I created this super-quick, no-frills tutorial so that I can remind myself how to navigate JSON objects whenever I’m rusty on the details.

Names of fields and values are kept as short as possible to minimize the amount of typing time.

This tutorial is designed for software engineers who are already comfortable with JSON — new developers should get some hands-on experience first.

Getting Started

Make sure you have the Node.js runtime installed on your device first — check here for the latest downloads.

Open the terminal, type ‘node’, and hit ENTER.

If Node is installed correctly you should see a welcome message and the version of Node you’ve got:

Copy and paste the following JSON object into the terminal window and press ENTER:

var x = {
a: 1,
b: 'b1',
c: true,
d: null,
e: undefined,
f: ['f1','f2'],
g: { 'g1': 10, 'g2': 20 },
h: {
'h0': {
'h01': 'test',
'h02': 10
},
'h1': [ 'h11', 'h12' ],
'h2': [ 'h21', 'h22' ]
}
};

We’re now ready to begin working with this JSON object!

Basics

x['a'];     // 1
x['b']; // 'b1'
x['c']; // true
x['d']; // null
x['e']; // undefined
x['z']; // undefinedx.c; // true
x.z; // undefined

Arrays

x.f;        // [ 'f1', 'f2' ]
x.f[0]; // 'f1'
x.f[1]; // 'f2'
x.f[2]; // undefined

Objects

x.g;      // { g1: 10, g2: 20 }
x.g.g1; // 10
x.g.g2; // 20
x.g.g3; // undefined

Nested Arrays and Objects

x.h;         // {
// h0: { h01: 'test', h02: 10 },
// h1: [ 'h11', 'h12' ],
// h2: [ 'h21', 'h22' ]
// }
x.h.h0; // { h01: 'test', h02: 10 }x.h.h0.h01; // 'test'
x.h.h0.h02; // 10
x.h.h1; // [ 'h11', 'h12' ]
x.h.h1[0]; // 'h11'
x.h.h1[1]; // 'h12'
x.h.h2; // [ 'h21', 'h22' ]
x.h.h2[0]; // 'h21'
x.h.h2[1]; // 'h22'

Thanks for reading! Let me know what you think in the comments section below, and don’t forget to subscribe 👍

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
George Marklow

George Marklow

98 Followers

George is a software engineer, author, blogger, and abstract artist who believes in helping others to make us happier and healthier.