Nested JSON Challenge

Lesson Details:
November 30, 2020

I: Introduction

Json is an industry standard for data interchange. It is a text based format for storing structured data. It has recently become more popular due to its use in web development.

A: Json quick introduction to json data

Json stores information as key value pairs. The key is similar to a column name. The value, the data itself. The key must be a string and the value can be any type of data. The key / value pairs are separated by commas, the same as sql. The value can be anything that is parsable by javascript, including arrays and objects.

Json can represent complex types such as nested objects and arrays. Javascript uses closures which means that you can refer to variables and functions defined outside of a function, even if they are declared after the function call. This is useful when dealing with part of an object or array inside another object or array without having to declare all of those pieces as global variables.

For example:

{ "a": { "b": { "c": { "d": 123 }, "e": 456 } } }

II: Body

A: Nested json challenge

Consider the following json object:

{ "name": "jason", "age": 23, "friends": [ { "name": "john" }, { "name": "sarah" }, { "name": "steve" } ] }

Write a program that takes this json object and outputs the name of the friends of jason . You will need to use one or more of the following techniques:

Recursive call (call a function from within the function)

Closures (refer to variables defined outside of the function)

The ... operator (unpack an array)

A closure is a piece of code that has access to variables and functions defined outside of the function call. In other words it is a block of code that is constrained to a specific context, a set of variables and functions that it can access. The closure references a variable x from within a function f, f() has access to x even though x was declared outside of the function. This is useful for writing code that uses some part of an object or array without defining it as global.

Closure Example:

function g() { var x = 7; return function () { return x + 1; } } var f = g(); alert(f()); // 8 alert(x); // 7

The ... operator can unpack an array into a list of variables named a, b, c, d, etc. This is useful if you want to write a function that calls a lot of other functions but you don't know how many there will be ahead of time. A basic example would be something like this: function foo(x) { alert(x); } foo(1); foo(2); foo(3); A more complex example would be something like this: var func = function () { var x = 1; var y = 2; var z = 3; return [x, y, z]; }; func(); // [1, 2, 3]

Course content