AlgoDaily Solution

1function parseJSON(input) {
2
3    // if the input is empty or starts with an invalid character, throw an error
4    if (input === "" || input[0] === "'") {
5        throw Error();
6    }
7
8    // check if the input is null, an empty object, empty array, or a boolean and return the value from the input
9    if (input === "null") {
10        return null;
11    }
12    if (input === "{}") {
13        return {};
14    }
15    if (input === "[]") {
16        return [];
17    }
18    if (input === "true") {
19        return true;
20    }
21    if (input === "false") {
22        return false;
23    }
24
25    //if the input starts with a quote, return the value from inside the quotes
26    if (input[0] === '"') {
27        return input.slice(1, -1);
28    }
29
30    // if it starts with a bracket, perform parsing of the contents within the brackets
31    if (input[0] === "{") {
32        return input
33            .slice(1, -1)
34            .split(",")
35            .reduce((acc, item) => {
36                // get the key and the value of the JSON property by splitting the string on the colon character
37                const index = item.indexOf(":");
38                const key = item.slice(0, index);
39                const value = item.slice(index + 1);
40                acc[parseJSON(key)] = parseJSON(value);
41                return acc;
42            }, {});
43    }
44    // if the input is an array, return the value from inside the array
45    if (input[0] === "[") {
46        return input
47            .slice(1, -1)
48            .split(",")
49            .map((x) => parseJSON(x));
50    }
51}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.