-1

I have an object like this.

var obj = {
    name: "foo",
    age: 23
};

for (i in obj) {
    if (obj[i] == "foo") {
    obj[i] = "bob";
  }
}

After manipulating the object
when using JSON.stringify(obj) i getting the output like this.

{"name":"bob","age":23}

But i don't need the objects property as string how to convert into objects property name. so i need the ouput like this {name:"bob",age:23}. Please correct me if i am wrong.

htoniv
  • 1,658
  • 21
  • 40

5 Answers5

3

This looks like the right output.

In the wiki the example looks the same WIKI JSON

In JS that shouldnt be a problem at all.

Pls look at this to parse your JSON string back to an object JSON.parse

Maybe it would be smarter to tell us why you need to remove the double qoutes from the key. Probably JSON is not the problem, I would look at the implementation.

Opaldes
  • 193
  • 1
  • 10
1

You don't need to do this, as {"name":"bob","age":23} is valid JSON. But if you really want to remove the quotes around the keys:

var json = JSON.stringify(obj);
var keyVals = json.substr(1,json.length-2).split(/,/g);

var output = "{";
keyVals.forEach(function(keyVal) {
   var parts = keyVal.split(":");
   output += parts[0].replace(/"/g, "");
   output += ":";
   output += parts[1];
   output += ",";
});

output = output.substr(0, output.length - 1);

output += "}";
Joe
  • 2,500
  • 1
  • 14
  • 12
1

As Anirudha said. if you want to remove the double quote of keys, you need regular expression. As fllows:

JSON.stringify(obj).replace(/"([^"]*)":/g, '$1:')
catssay
  • 106
  • 5
0

Yes we can use the regular expression to solve this problem

console.log(JSON.stringify({"name":"bob","age":23}).replace(/\"([^(\")"]+)\":/g,"$1:"))
htoniv
  • 1,658
  • 21
  • 40
  • Sorry to answer my own question. but without using regExp i need the solution – htoniv Nov 23 '16 at 10:44
  • I know JSON.stringify converts key values in to string. but i dont need the output like this. please understand my question. – htoniv Nov 23 '16 at 10:45
0

Parsing an object with JSON.stringify(obj) does not read just your properties values, but also your properties names in order to transform an object into a JSON string ( example syntax style look in package.json where bouth properties and values have parenthases ). Your object properties become strings because the object is stringified, so if you dont want properties to be strings don use JSON.stringify() on the object.

enovz
  • 11
  • 1
  • 2