Json in JavaScript

Our first program will demonstrate JSON encoding and decoding in JavaScript. Here’s the full source code:

// We'll use these two objects to demonstrate encoding and
// decoding of custom types below.
const response1 = {
    page: 1,
    fruits: ['apple', 'peach', 'pear']
};

const response2 = {
    page: 1,
    fruits: ['apple', 'peach', 'pear']
};

function main() {
    // First we'll look at encoding basic data types to
    // JSON strings. Here are some examples for atomic
    // values.
    console.log(JSON.stringify(true));
    console.log(JSON.stringify(1));
    console.log(JSON.stringify(2.34));
    console.log(JSON.stringify("gopher"));

    // And here are some for slices and maps, which encode
    // to JSON arrays and objects as you'd expect.
    const slcD = ["apple", "peach", "pear"];
    console.log(JSON.stringify(slcD));

    const mapD = { "apple": 5, "lettuce": 7 };
    console.log(JSON.stringify(mapD));

    // The JSON.stringify method can automatically encode your
    // custom data types.
    console.log(JSON.stringify(response1));
    console.log(JSON.stringify(response2));

    // Now let's look at decoding JSON data into JavaScript
    // values. Here's an example for a generic data
    // structure.
    const byt = '{"num":6.13,"strs":["a","b"]}';

    // Here's the actual decoding, and a check for
    // associated errors.
    try {
        const dat = JSON.parse(byt);
        console.log(dat);

        // We can access the values in the decoded object
        // directly without type assertions.
        const num = dat.num;
        console.log(num);

        const strs = dat.strs;
        const str1 = strs[0];
        console.log(str1);
    } catch (error) {
        console.error("Error parsing JSON:", error);
    }

    // We can also decode JSON into custom data types.
    // This has the advantage of adding additional
    // type-safety to our programs when using TypeScript.
    const str = '{"page": 1, "fruits": ["apple", "peach"]}';
    const res = JSON.parse(str);
    console.log(res);
    console.log(res.fruits[0]);

    // In JavaScript, we can directly stringify objects to JSON
    // and write them to streams or files.
    const d = { "apple": 5, "lettuce": 7 };
    console.log(JSON.stringify(d));
}

main();

To run the program, save it as json.js and use node:

$ node json.js
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
{ num: 6.13, strs: [ 'a', 'b' ] }
6.13
a
{ page: 1, fruits: [ 'apple', 'peach' ] }
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in JavaScript here, but check out the MDN JSON documentation for more information.

JavaScript has built-in support for JSON through the JSON object, which provides methods for parsing JSON strings (JSON.parse()) and converting JavaScript objects to JSON strings (JSON.stringify()). Unlike Go, JavaScript doesn’t require explicit type declarations or conversions when working with JSON data, making it more straightforward in many cases.