Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify().

Presenting my current implementation below -

var my_json_encode = function(input) {

  if(typeof(input) === "string"){
      return '"'+input+'"'
  }
  if(typeof(input) === "number"){
      return `${input}`
  }

  if(Array.isArray(input)) {
     const formattedArrayMembers = input.map(value => my_json_encode(value)).join(',');
     return `[${formattedArrayMembers}]`;
  }

  *****Issue lies here*******
  if(typeof(input) === "object" && !Array.isArray(input)) {
    let temp = "";
    for (let [key, value] of Object.entries(input)) {
            let val = `${key} : ${value}`;
            temp +=  my_json_encode(val)
    }
    return `{${temp}}`
  }
}
Current input is -> {"key1":"val1","key2":"val2"}
Expected output is -> {"key1":"val1","key2":"val2"}

Current output using object type check in my_json_encode -> {"key1 : val1""key2 : val2"}

Feels like I'm close but there's a missing piece in my logic. Been staring at this for too long and could use some guidance.

If I can get the object encoder working, I believe I can recursively apply it to handle more complex inputs like:

Expected Output-> [1,"a",{"key1":"value1","key2":null,"key3":[4,"b"],"key5":{"inner1":"innerval1","inner2":9}}]

Had a similar question regarding converting an array to a JSON string answered here

Answer №1

The primary concern revolves around enclosing the entire key in double quotes when iterating through the entries and utilizing my_json_encode for the value:

"${key}: ${my_json_encode(value)}"

Additionally, each key-value pair should be connected with a ,, achieved by converting each pair into the mentioned string format and then concatenating them using .join(',').

Escaping any occurrences of " within keys or string values is necessary, along with understanding that typeof functions as an operator rather than a function - it can be employed like typeof someVar:

var my_json_encode = function(input) {

  if (typeof input === "string") {
    return '"' + input.replace(/"/g, '\\"') + '"'
  }
  if (typeof input === "number") {
    return input;
  }

  if (Array.isArray(input)) {
    const formattedArrayMembers = input.map(my_json_encode).join(',');
    return `[${formattedArrayMembers}]`;
  }
  if (input === null) return 'null';
  // If it's not an array, it's a non-array object
  const keyValStrArray = Object.entries(input).map(([key, val]) => (
    `"${key.replace(/"/g, '\\"')}":${my_json_encode(val)}`
  ));
  return `{${keyValStrArray.join(',')}}`;
};

console.log(my_json_encode({ "key1": "val1", "key2": "val2" }));
console.log(my_json_encode([1,"a",{"key1":"value1","key2":null,"key3":[4,"b"],"key5":{"inner1":"innerval1","inner2":9}}]));

Answer №2

To handle objects, you can create an array called temp and push key-value pairs as key: my_json_encode(value) to it. Then concatenate them with , before enclosing the result in curly braces {}:

var my_json_encode = function(input) {

  if (input === null) {
    return "null";
  }

  if (typeof(input) === "string") {
    return `"${input}"`;
  }
  if (typeof(input) === "number") {
    return `${input}`;
  }

  if (Array.isArray(input)) {
    const formattedArrayMembers = input.map(value => my_json_encode(value)).join(',');
    return `[${formattedArrayMembers}]`;
  }

  if (typeof(input) === "object") {
    let temp = [];
    for (let [key, value] of Object.entries(input)) {
      temp.push(`"${key}" : ${my_json_encode(value)}`);
    }
    return `{${temp.join(', ')}}`;
  }
}

console.log(my_json_encode({key1:"val1",key2:3}));
console.log(my_json_encode([1,"a",{"key1":"value1","key2":null,"key3":[4,"b"],"key5":{"inner1":"innerval1","inner2":9}}]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an HTML table from an array in an email using PHP

How can I use data collected by Javascript to generate an email in PHP? The array structure in JavaScript is like this: Menu[ item(name,price,multiplier[],ingred), item(name,price,multiplier[],ingred) ] The array Menu[] is dynamically cr ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

Adding specific key, value pairs to a python dictionary by extracting data from a json file

I am facing an issue where I need to extract a specific key and value from a JSON file in Python and add it to a dictionary. Currently, I have been able to successfully add all the data from the JSON file into my dictionary, but that is not the desired out ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...

Testing a Jest unit on a function that invokes another function which in turn returns a Promise

I have a function that triggers another function which returns a Promise. Below is the code snippet for reference: export const func1 = ({ contentRef, onShareFile, t, trackOnShareFile, }) => e => { trackOnShareFile() try { func2(conte ...

What techniques can be employed to utilize multiple JavaScript files?

Hey there, I am facing an issue while trying to execute multiple JavaScript codes. My first script is running smoothly with the change function, but the second one seems to be causing some trouble. Can anyone guide me on how to effectively run multiple J ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

Navigating through JSON arrays with Node.js

I have been given the task of iterating through a complex JSON file that contains an array of JSON objects. I am finding it difficult to access the array object within the JSON file. Specifically, I need to access the "class-name" object from the JSON f ...

Organizing an array of objects by sorting them according to their internal data and grouping them together

Looking to organize this array of objects in a hierarchical structure: var channels = [{ cid: 5, pid: 10 }, { cid: 10, pid: 0 }, { cid: 20, pid: 5 }, { cid: 15, pid: 10 }]; In this case, cid represents channel Id and pid r ...

Submitting dataURL via Ajax using multipart/form-data

I'm currently working on a program that is responsible for extracting a dataURL from a canvas element and then transmitting it to the server side for conversion back into a JPG file. Now, my next step involves retrieving this image from the server pro ...

Is there a way to convert a Java object into a JSON format in Java without relying on external libraries or dependencies?

public class Information { private String privilege; private String bar; private Int years; } transformed into {"privilege" : "data", "bar": "data", "years":"data"} devoid of Gson or Jackson. solely using core Java Is there a simpler approac ...

Looping through an array of JSON objects without keys in Java for an Android application

I am looking to loop through a JSON array containing objects, but all the tutorials I've found are for keyed JSON objects. This is how the JSON array appears: items:[{i know}, {what you did} ,{last summer}] ...

Different methods to disable scrolling when the mobile menu pops up

I have implemented a mobile menu option that appears when you click on the triple line logo, but unfortunately, users can still scroll while the menu is open. I've tried using position:fixed; but haven't been successful in preventing scrolling be ...

Stopping the setTimeout function triggered by a click event in a Reactjs application

I'm a beginner with Reactjs and I ran into a dilemma while using setTimeOut. I couldn't figure out whether to use clearTimeOut or stopPropagation() to stop it. Here's my code: render: function() { return ( < div className = "colorCl ...

Unable to assign a value to a constant within the class constructor

I'm aware that in TypeScript, readonly properties can only be assigned a value within a class constructor. However, I encountered an error while trying to do so inside the constructor of my class, specifically related to an array method handler. class ...

Sorting a JSONArray in Java Android according to its keys - the ultimate guide

Upon receiving this data from a web service, it is structured in a JSONArray as shown below: [ { "lat": "-16.408545", "lon": "-71.539105", "type": "0", "distance": "0.54" }, { "lat": "-16.4244317845", "lon": "-71.52562186", "type": "1", ...

It appears that the functionality of RegExp.prototype.exec() is not functioning as expected

const fs = require('fs') const jsdocFinder = /\/\*\*\n(.+?)\*\//gs /** * Implementing a function to convert JSDocs into JSON format. * @function * @param {String[] | String} dirs The directory or directories of ...

(NodeJS + Socket IO Issue) NodeJS is sending duplicate data when the page is refreshed, causing an improper response

Each time I refresh a page, NodeJS seems to be repetitively writing data on the socket. Interestingly, the number of writes increases with each page refresh but then stabilizes at three after several refreshes. I urge you to inspect the console output whi ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...