Convert Object to JSON String in JavaScript

Oct 4, 2023 ยท 5 min read

Overview

Converting a JavaScript object to a JSON string is a common task when working with data in web applications. While JavaScript provides a built-in JSON.stringify() method to accomplish this, understanding how it works under the hood is useful.

In this article, we'll go over a few key concepts for working with JSON in JavaScript. We'll also walk through an implementation of a jsonStringify function to convert an object to a valid JSON string.

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight data format that is used for serializing and transmitting data over the web.

JSON is based on a subset of JavaScript syntax, but the two are not the same. While JavaScript is a programming language, JSON is a data interchange format.

Here are some key characteristics of JSON:

  • JSON is text-based and completely language independent. Any programming language can generate and parse JSON.
  • JSON requires using double quotes around keys and string values.
  • JSON requires keys to be strings wrapped in double quotes.
  • JSON values can be:
  • JSON uses a key/value structure to store data.
  • Data is serialized in { } brackets for objects and [ ] for arrays.
  • For example:

    {
      "name": "John",
      "age": 30,
      "hobbies": ["coding", "tennis"]
    }
    

    JSON is useful for transmitting structured data over networks and web services. It is lighter and simpler than XML. JSON is easy to read and parse for humans and machines alike. This makes it ideal for client-server communication and web applications.

    Key Concepts

    Here are some key things to understand about JSON in JavaScript:

    JSON Structure

    A valid JSON string requires:

  • Objects wrapped in {}
  • Arrays wrapped in []
  • Keys and strings in "" quotes
  • Key/value pairs separated by :
  • Elements separated by , comma
  • For example:

    {"name":"John", "age":30, "hobbies":["coding", "tennis"]}
    

    JavaScript Types

    When converting a JavaScript object to JSON, we need to handle:

  • Primitive types: strings, numbers, booleans
  • Complex types: objects, arrays
  • Edge cases: null, undefined
  • JavaScript provides ways to detect the type of a value like typeof and Array.isArray().

    Recursion

    Since objects can be nested, we need to recursively stringify nested values.

    For example:

    let obj = {
      name: "John",
      address: {
        street: "123 Main St",
        city:"New York"
      }
    }
    

    To handle nested objects like above, we need to recursively call jsonStringify on nested object values.

    Implementation

    With those concepts in mind, here is an implementation of jsonStringify to convert a JavaScript object to a JSON string:

    function jsonStringify(obj) {
    
      // Base case for null
      if (obj === null) {
        return 'null';
      }
    
      // Base case for undefined
      if (obj === undefined) {
        return 'undefined';
      }
    
      // Objects and Arrays need recursion
      if (typeof obj === 'object') {
        if (Array.isArray(obj)) {
          // Array
          let str = '[';
          str += obj.map(value => jsonStringify(value)).join(',');
          str += ']';
          return str;
        } else {
          // Object
          let str = '{';
          let entries = Object.entries(obj);
          str += entries.map(entry => {
            return `"${entry[0]}":${jsonStringify(entry[1])}`;
          }).join(',');
          str += '}';
          return str;
        }
      }
    
      // Primitives just need converting to a string
      if (typeof obj === 'string') {
        return `"${obj}"`;
      }
      if (typeof obj === 'number' || typeof obj === 'boolean') {
        return obj.toString();
      }
    
    }
    

    Let's break down what's happening:

  • Check for null and undefined and handle those base cases
  • Use typeof to check if it's an object/array
  • For Arrays:
  • For Objects:
  • For primitives, convert to a string as needed
  • And that's it! This provides the overall logic to handle all the cases of stringifying a JavaScript object.

    Here is an example of using jsonStringify on a sample object:

    const obj = {
      name: "John",
      age: 30,
      hobbies: ["coding", "tennis"]
    };
    
    jsonStringify(obj);
    
    // Returns:
    // {"name":"John","age":30,"hobbies":["coding","tennis"]}
    

    Converting JSON String to Object

    We can also go the other way and parse a JSON string into a JavaScript object. This is useful when receiving JSON data from a web API.

    JavaScript provides a built-in JSON.parse() method to convert JSON into a native JavaScript object.

    For example:

    const json = '{"name":"John", "age":30, "hobbies":["coding", "tennis"]}';
    
    const obj = JSON.parse(json);
    
    // obj is now a JavaScript object
    // {name: "John", age: 30, hobbies: ["coding", "tennis"]}
    

    JSON.parse() takes a valid JSON string and transforms it into a JavaScript object.

    It will parse primitive types like numbers, strings, and booleans into their JavaScript equivalents.

    It will parse JSON arrays into JavaScript arrays.

    And JSON objects into JavaScript objects, with key/value pairs.

    This makes it straightforward to get data received as JSON into a format you can work with in JavaScript.

    Some things to note about JSON.parse():

  • It will throw an error if the JSON is invalid.
  • JSON keys become JavaScript object properties.
  • It can recursively parse nested objects and arrays.
  • Date ISO strings (e.g. "2022-01-01T00:00:00.000Z") will get parsed into JavaScript Date objects.
  • Summary

    Converting a JavaScript object to a valid JSON string requires carefully handling types like objects, arrays, and primitives. Recursively stringifying nested values is key.

    While JavaScript provides JSON.stringify(), implementing it yourself helps demystify working with JSON in JS.

    Here are some key takeaways:

  • Use typeof and Array.isArray() to detect types
  • Stringify primitive values
  • Recursively stringify nested object/array values
  • Wrap objects with { } and arrays with [ ]
  • Separate key/value pairs and elements with , comma
  • Return valid JSON syntax
  • Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: