srp321
srp321

Reputation: 116

Converting json String to Object in Javascript

I have the following text in form of var in JS which i am getting from another function.

    var text = '["{"a1":"zxcv","a2":"pqrs","c2":[1,2,3],"a3":{"aa3":"asdfgh","aa5":null}}","{"a1":"xyz","a2":"mno","c2":[103],"a3":{"aa8":"qwerty"}}"]';

I have a requirement to check the count of a1, a2, c2 and it's values and a3 and its values as well. such as: a1: 2, a2: 2, c2: 4, a3: 3 and so on (count of child elements as well)

The crude way i could think to get my result was to 1st remove the first and last " and replace }","{ with },{ This gave me a json array of objects and using JSON.parse gave me a better structure converted then i could traverse easily on that. I couldn't find any library or other solution as alternative to this.

 var text = '["{"a1":"zxcv","a2":"pqrs","c2":[1,2,3],"a3":{"aa3":"asdfgh","aa5":null}}","{"a1":"xyz","a2":"mno","c2":[103],"a3":{"aa8":"qwerty"}}"]';

        console.log(text);

        text = text.replace(/\["{/g, "[{"); // remove first double quote
        text = text.replace(/\}"]/g, "}]"); // remove last double quote
        text = text.replace(/\}","{/g, "},{"); // replace middle quotes

        console.log(text);

        var formattedText = JSON.parse(text);

        console.log(formattedText);

Expected output after i get it in a object form as then i can loop over object and use counter to maintain count:

a1: 2, a2: 2, c2: 4, a3: 3

Is there any function (inbuilt or with a library) that can help me with this?

Upvotes: 0

Views: 120

Answers (1)

georg
georg

Reputation: 214949

You can try fixing that string by removing quotes that are not key/value delimiters and parse the result as a json:

var text = '["{"a1":"zxcv","a2":"pqrs","c2":[1,2,3],"a3":{"aa3":"asdfgh","aa5":null}}","{"a1":"xyz","a2":"mno","c2":[103],"a3":{"aa8":"qwerty"}}"]';


t = text
    .replace(/"([^"]+)":/g, '@$1@:')
    .replace(/:"([^"]+)"/g, ':@$1@')
    .replace(/"/g, '')
    .replace(/@/g, '"')


console.log(JSON.parse(t))

If you're interested in what these replacements do exactly, here's a step-by-step visualization:

var text = '["{"a1":"zxcv","a2":"pqrs","c2":[1,2,3],"a3":{"aa3":"asdfgh","aa5":null}}","{"a1":"xyz","a2":"mno","c2":[103],"a3":{"aa8":"qwerty"}}"]';

String.prototype.show = function(s) {
  console.log(s + ": " + this);
  return this;
}


t = text
    .show('Init')
    .replace(/"([^"]+)":/g, '@$1@:')
    .show('Step 1')
    .replace(/:"([^"]+)"/g, ':@$1@')
    .show('Step 2')
    .replace(/"/g, '')
    .show('Step 3')
    .replace(/@/g, '"')
    .show('Step 4')

Upvotes: 2

Related Questions