HomeContact
NodeJS
How to automatically parse JSON stored in a string with NodeJS and Javascript.
April 07, 2022
1 min

Let’s see how to automatically parse JSON at a different level in a requested object (from MySQL or other databases that store objects in a string) and sanitize it using NodeJS and Javascript.

This will also work in vanilla javascript or a frontend framework like React or Vuejs. But most of the time, you’ll get clean data from your backend.

As you may know, some databases can store large JSON directly in a string like Mysql.

When you request it, you may end up with some object looking like this :

const obj = {
  user: "{ name: 'Bob', age: 31, mail: 'bob@mail.com' }"
}

And you want to quickly change that so that your NodeJS app can access it like an ordinary object.

To do so, simply use :

const sanitizedObj = JSON.parse(obj)

You will end up with a clean usable object to use in NodeJS like this one :

const sanitizedObj = {
  user : {
    name: "Bob",
    age: 31,
    mail: "bob@mail.com"
  }
}

Pretty easy, right? Now let’s spice things a bit because your first request JSON will not have only one entry to parse most of the time. What if it has several more like this :

const obj = {
  id : 123
  text: 'random text',
  user: "{ name: 'Bob', age: 31, mail: 'bob@mail.com' }",
  personal : "{ street: 'Main Street', number: 10, city: 'Miami' }"
  pro: "{ street: 'Pro Street', number: 25, city: 'New York' }"
}

You get the idea, several JSON to parse, but in your object you will have Number as well as other string that are not JSON. We need a function that will detect if there is a JSON to parse, and do nothing if it’s not one:

const autoParseJSON = (obj) => {
  let parsedResult = {};
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value == "string" && value.indexOf('{') >= 0) {
      parsedResult[key] = JSON.parse(value);
    } else {
      parsedResult[key] = value;
    }
  }
  return(parsedResult);
};

This function takes an object as an entry and will loop through all attributes using Object.entries. It checks if the value is a string with typeof and finally checks if the string is an object by checking if it contains a bracket with value.indexOf('{') >= 0). We assume here that a bracket will not appear elsewhere for other use. We then parse the JSON and add it to a newly created object if all checks are good. If it’s not a JSON, we add it to the new object to avoid data loss. We end the function by returning our newly created object.

Finally, what if the request object is an Array filled with objects that have JSON to be parsed? It’s what returns most MySQL queries, for example :

const array = [
  {
    id : 123
    text: 'random text',
    user: "{ name: 'Bob', age: 31, mail: 'bob@mail.com' }",
    personal : "{ street: 'Main Street', number: 10, city: 'Miami' }"
    pro: "{ street: 'Pro Street', number: 25, city: 'New York' }"
  },
  {
    id : 1234
    text: 'random text',
    user: "{ name: 'Alice', age: 25, mail: 'alice@mail.com' }",
    personal : "{ street: 'Main Street', number: 12, city: 'Miami' }"
    pro: "{ street: 'Pro Street', number: 15, city: 'New York' }"
  },
]

We can simply loop through this array using our previous autoParseJSON() function :

const autoParseArrayWithJSON = (array) => {
  const parsedArray = array.map(obj => autoParseJSON(obj))
}

You’ve seen how to clean JSON data stored in a string, probably in MySQL. You know how to parse whatever you obtain from your request automatically, depending on the data structure using Javascript and NodeJS.


Tags

javascriptnodejs

Related Posts

How to call a route internally using NodeJS
April 11, 2022
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media