Aaron
Aaron

Reputation: 4480

JSON.parse not working for changing a string into an object

I have a string

{ city : Chicago , country : us , name : Somebody , plan : quarter90wtrial },{ city : New York , country : us , name : Somebody , plan : quarter90wtrial },{ city : Portland , country : us , name : Somebody , plan : quarter90wtrial },{ city :null, country :null, name : Somebody , plan : quarter90wtrial },{ city : Mexico City , country : mx , name : Aaron , plan : quarter90wtrial },{ city : Boston , country : us , name : Somebody , plan : quarter90wtrial },{ city : Los Angeles , country : us , name : Somebody , plan : quarter90wtrial },{ city : London , country : gb , name : Aaron , plan : quarter90wtrial },{ city : Los Angeles , country : us , name : Aaron , plan : quarter90wtrial },{ city : Chicago , country : us , name : Aaron , plan : quarter90wtrial }

What I am trying to do is turn this string into an object where I can iterate and print out the city, country, and name for each one. So far I have figured out how to split the string to print out each line individually.

str = str.split('},{');
for(var i =0; i < str.length; i++)
{
      alert(str[i]);
}

What I cannot figure out is how to convert the string to an object where I can print out the city, country, name, etc.

Upvotes: 0

Views: 58

Answers (1)

Washington Guedes
Washington Guedes

Reputation: 4365

You had the correct initial idea.

However, after the split method, you will still need to map every pair of key:value like this:

var str = '{ city : Chicago , country : us , name : Somebody , plan : quarter90wtrial },{ city : New York , country : us , name : Somebody , plan : quarter90wtrial },{ city : Portland , country : us , name : Somebody , plan : quarter90wtrial },{ city :null, country :null, name : Somebody , plan : quarter90wtrial },{ city : Mexico City , country : mx , name : Aaron , plan : quarter90wtrial },{ city : Boston , country : us , name : Somebody , plan : quarter90wtrial },{ city : Los Angeles , country : us , name : Somebody , plan : quarter90wtrial },{ city : London , country : gb , name : Aaron , plan : quarter90wtrial },{ city : Los Angeles , country : us , name : Aaron , plan : quarter90wtrial },{ city : Chicago , country : us , name : Aaron , plan : quarter90wtrial }';

var result = str.split('},{').map(function(itemStr) {
    var itemObj = {};

    // here we map each "key:value" pair
    itemStr.replace(/.*?(\w+) *: *(.*?) *[,}]/g, function(match, key, val) {
        itemObj[key] = val;
    });
    return itemObj;
});

console.log(result)

You can see how the regular expression is working here: https://regex101.com/r/E5tg26/1

Hope it helps.

Upvotes: 2

Related Questions