Building clean JSON strings that can be parsed in JavaScript

Posted by admin at January 6, 2021

Certain tasks required dynamically building JSON strings that are then parsed, transmitted and used in other media of different languages. This is usually encountered when coding products using multi-language stacks for instance when building APIs.

Building and consuming JSON within JavaScript is very easy as the convention belongs to the scripting language and lot of extra delimiters, missing quotes are forgiven when parsing the string. JavaScript converts string to object using the parse() method and converts JSON objects to string using the method

// parse a string into JSON
  let jsonObject = JSON.parse(jsonString)

  // convert object to string
  let jsonString = JSON.stringify(jsonObject)

However, problems arise when it is required to construct JSON objects on a different medium other than JS and then transmit the string to JS. The aim of this article is to define a convention for constructing JSON string in any language that will be used in JavaScript.

In JavaScript, JSON notations are clear and distinguishable. You can tell what part is the property and what part is the value, you can organize the JSON objects into arrays really quickly. However when building a string that you intent to parse with JavaScript, ensure the following steps are taken:

1. Use collections: arrays, dictionaries and lists to store data and then convert them to JSON string:

Certain languages have methods that enable you convert data collections such as associative arrays into strings of JSON format. PHP has json_encode(), Python has json.dumps() and json.loads(). Simply put the data items into associative arrays with appropriate keys and then convert the collection into JSON string.

/**
        * Converting an associative array with Php
        */

        // save the data
        $data = [
            "name" => "BlinkWiki",
            "message" => "Handcoding JSON Strings",
            "count" => 36
        ];

        // encode the JSON and print
        echo json_encode($data);
/**
        * Converting a list with Python
        */

        # import the library
        import json

        # save the data
        data = ["BlinkWiki", "Handcoding JSON Strings", 36]

        # covert the list to json
        jsonString = json.dumps(list)

        # show the string result
        print(jsonString)

        // json string
        jsonString = '{"name": "BlinkWiki", "message":"Handcoding JSON Strings", "count": 36}'
"""
    Converting a dictionary with Python
   """

   # save the data into a dictionary
   data = {
      "name": "BlinkWiki",
      "message": "Handcoding JSON Strings",
      "count": 36
   }

   # parse the dictionary
   with open('app.json', 'w', encoding='utf-8') as f:

      # and dump out each line
      json.dump(data, f, ensure_ascii=False, indent=4)

NOTE: Sometimes this approach will generate a functional JSON string that can only be parsed in the language, especially if you are not using frameworks and you are relying on native functions. For this article we require JSON strings that can be parsed in JavaScript even though they originated in other languages.

2. Take advantage of a framework:

Also if you are using frameworks (which you should be when building large API products), utilize the the full provisions provided by these frameworks. Certain frameworks provide functions that allows you convert arrays and lists into clean JSONstrings. PHP’s Laravel has Response::json() and Python has JsonResponse(). These functions properly clean and serialize the collection for you. Take advantage of them.

/**
        * Converting a dictionary with PHP Laravel
        */

        // include the request library
        use Illuminate\Http\Request;

        // save the data into a dictionary
        $data = [
            "name" => "BlinkWiki",
            "message" => "Handcoding JSON Strings",
            "count" => 36
        ];

        // convert the using Laravel provisions
        $jsonString = response()
            ->json(data)
        ;

        // print the parse results
        return $jsonString;
"""
   Converting a dictionary with Python Django
   """

   # save the data into a dictionary
   data = {
      "name": "BlinkWiki",
      "message": "Handcoding JSON Strings",
      "count": 36
   }

   # convert the using Django JsonResponse()
   jsonString = JsonResponse(data)

   # print the parse results
   print(jsonString)

3. Encase keys and values strings in double quotes:

If the language you are working on does not have JSON converters for data collections, then you would have to build by hand. Building JSON in string format in another language, say PHP or Python, requires a certain important convention: the double quotes. Every property name and value MUST be encased in the double quotation marks:

$json = '{"name":"John Doe","age":"27","eye_color":"hazel","hair_color":"black"}'

So encase every node property and value in double quotation marks (“). Avoid single quotes (‘) and never use backticks (`) for encasing. Single quotes and backticks can however be used for encasing the entire string.

4. Trim all trailing commas:

Another rule, I adhere to is to ensure that there are no trailing commas inside JSON objects or array of objects. A piece of code such as the one below will result in problems when parsing on the JavaScript end:

// WRONG: notice the trailing comma at the end of the string
   $json = '{"name":"John Doe","age":"27","eye_color":"hazel"},';

   // CORRECT: there is NO trailing commas
   $json = '{"name":"John Doe","age":"27","eye_color":"hazel"}';

   // WRONG: there is a comma between the '}' and ']' at the end
   $json_array = '['
      .'{"name":"John Doe","age":"27","eye_color":"hazel"},'
      .'{"name":"Jane Dane","age":"29","eye_color":"blue"},]';

   // CORRECT: there is NO comma between the '}' and ']' at the end
   $json_array = '['
      .'{"name":"John Doe","age":"27","eye_color":"hazel"},'
      .'{"name":"Jane Dane","age":"29","eye_color":"blue"}'
   .']';

5. Escape string before transmission:

Finally for security purposes, ensure the strings are escaped before transmission and un-escaped post transmission. This is especially important when hand-coding your JSON string.

   0 likes

Suggested Read