user8000626
user8000626

Reputation: 305

create a json object from a string which contains keys and values

I have such strings which I get by manipulating the DOM. how can I convert them to javascript objects, so that I can later stringify them? please advise.

can I use JSON.parse with reviver?

str = "age: 65,  name: "Jay",  smoker: false"

thanks

Upvotes: 0

Views: 170

Answers (1)

Maycon Mesquita
Maycon Mesquita

Reputation: 4600

Let's start from beginning:

Your string has invalid json syntax: "age: 65, name: "Jay", smoker: false"

This is a valid json syntax: {"age": 65, "name": "Jay", "smoker": false}

After turn this valid, you could do just a simple parse:

var json = JSON.parse({"age": 65, "name": "Jay", "smoker": false});

However, do you need to convert your invalid string to a valid JS Object, right?

We can achieve it in that way:

  1. Firstly, your string need to be escaped:
var str = "age: 65,  name: \"Jay\",  smoker: false";
  1. Then, apply this split-map function:

str = str.split(',').map((str) => str.trim().substring(0, str.length).replace(': ', ':'));

  1. Finally, a loop to create the object, filtering unwanted prop types:
var obj = {};

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

  // "boolean" to boolean
  split[1] = split[1] === "true" ? true : split[1] === "false" ? false : split[1];

  // ""string"" to "string"
  split[1] = typeof split[1] === 'string' ? split[1].replace(/['"]+/g, '') : split[1];
    obj[split[0]] = split[1];
}

// results valid obj: { age: "6", name: "Jay", smoker: false }

Using this object, you can easily do JSON.stringify(obj) to get a valid json.

Of course, if you change your string structure, this functions will need re-work.

Upvotes: 1

Related Questions