8

How do I add quotation marks to a JSON Object attributes for example like this:

{name:"User 01"}

so it should look like that afterward:

{"name":"User 01"}

both of them are strings

5
  • Where are you seeing the first example? Javascript Object? Commented Mar 12, 2015 at 21:54
  • 1
    shift + 2, name, shift + 2... or have a missed the question? Commented Mar 12, 2015 at 21:54
  • Why do you need to do that? It's the same thing. Commented Mar 12, 2015 at 21:59
  • 2
    No it is not, the first is not valid JSON. Commented Mar 12, 2015 at 22:00
  • 2
    It's the same thing in JavaScript. Commented Mar 12, 2015 at 22:01

4 Answers 4

8

Assuming the first example is a Javascript object, you could convert it into a JSON string using JSON.stringify:

JSON.stringify({name:"User 01"});

outputs: "{"name":"User 01"}"

Assuming String

If the first example is a string, I think you would have to parse through it with methods like split.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I did not write it down; The important thing is, it is not a JSON object, it is a string, which is the output from JSON.stringify-ed JSON Object and the quotation marks from the attributes were deleted
Parsing via split is tricky if you want do it right, I.e. strings could contain colons or commas...
7
JSON.stringify(eval('{name:"User 01"}'));

Not really great but works.

2 Comments

Uhh, eval.. I don't like that, but anyway, that is exactly what I wanted! Thanks dude!
Jep, don't like it either but keeps you going until you find something better. Best practice is to add FIXME as a comment above. ;)
3

the first notation

var string = {name:"user 01"}

if you use it then you can directly access all the properties and methods of the string object

but if you use this notation :

var string = {"name":"user 01"}

then you have to use :

window.JSON.parse("'"+string+"'")

Update: Now that we have ES6, you can use template literals :

window.JSON.parse(`'${string}'`)

in order to access all the methods and properties of string object

the last notation is used generally when getting data back from php script or something like that

1 Comment

What JS implementation are you using that doesn't like var obj = { "name": "user 01" }? That's a perfectly-valid JS object literal.. the quotation marks around the key are optional if the key is a valid identifier, but always acceptable.
2

Use this:

function JSONify(obj){
  var o = {};
  for(var i in obj){
    o['"'+i+'"'] = obj[i]; // make the quotes
  }
  return o;
}
console.log(JSONify({name:'User 01'}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.