Parsing JSON Objects
The Curly Braces
In JSON, objects are wrapped in curly braces {}
. This will be our signal to dive deeper and parse the properties inside it.
The Approach
- Slice the Braces: Remove the starting and ending curly braces.
- Split Properties: Split the string by commas to get individual
"key": "value"
strings. - Key-Value Parsing: Use
indexOf(":")
to find where the key ends and the value starts, then slice the string to get both parts. - Recursive Parsing: We call the
parse
function recursively to handle nested objects.
JAVASCRIPT
1if (input[0] === "{") {
2 return input
3 .slice(1, -1)
4 .split(",")
5 .reduce((acc, item) => {
6 const index = item.indexOf(":");
7 const key = item.slice(0, index);
8 const value = item.slice(index + 1);
9 acc[parse(key)] = parse(value);
10 return acc;
11 }, {});
12}