11

I am trying to learn JSON, i learned that any javascript object with the key in double quotes are considered as JSON object.

And i constructed this object

var jstr1 = {"mykey": "my value"};

But when i try to parse using JSON.parse(jstr1), i got the following error. see the screenshot.

enter image description here

But when i try to parse this

var jstr = '{"mykey": "my value"}';,

i got the success, see the screenshot. i got confused with this. Please explain me why this happens. what is the difference between the two forms.

And when i got JSON as a response from any services, how it would look like, whether it will be in form of jstr or jstr1

thanks in advance for any help.

Mohamed Hussain
  • 7,433
  • 14
  • 55
  • 85

5 Answers5

34

You are creating a Javascript Object. If you want a JSON-string from it, use JSON.stringify.

So

const myObj = {mykey: "my value"};
const myObjJSON = JSON.stringify(myObj);

Based on comments: There is no such thing as a JSON Object. There are JSON-strings, which can be parsed to Javascript Objects. Javascript Objects can be stringified to JSON strings. Within a JSON-string keys and values are quoted. So the result of the above is a string containing '{"mykey":"my value"}'.

Try parsing myObjJSON in your browser console (using: JSON.parse(myObjJSON)) and you get: Object {mykey: "my value"}.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • @Kooilnc In ur answer, even though the mykey is not in double quotes as specified by JSON standards, it is converted to JSON string."var myObj = {mykey: "my value"}". I got the same result when i stringify the object with mykey with or without quotes. – Mohamed Hussain Sep 05 '13 at 11:44
  • @MohamedHussain The keys don't have to be enclosed by double quotes in *JavaScript*. – ComFreek Sep 05 '13 at 11:47
  • @ComFreek you are correct. keys not neccessary for to be in quotes but for JSON, they key needed to be in double quotes, i learned this from http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation?lq=1 – Mohamed Hussain Sep 05 '13 at 11:52
  • @MohamedHussain: in a javascript `Object` there's no need for quoting key names, unless the key name contains spaces. Also check http://net.tutsplus.com/tutorials/javascript-ajax/cargo-culting-in-javascript/?utm_source=buffer – KooiInc Sep 05 '13 at 12:18
  • @Kooilnc you are correct javascript object key does not need quotes. My question is does JSON Object key requires double quotes?. – Mohamed Hussain Sep 05 '13 at 12:41
  • @Kooilnc: Thanks For mentioning there is no JSON Object. Normal Javascript object can be converted into JSON String. If normal Javascript object key, doesn't have double quotes when stringify to JSON string, double quotes is added in JSON string. If quotes is already present also same result when stringify from Javascript object to JSON string – Mohamed Hussain Sep 05 '13 at 13:04
  • It should be `'{"mykey":"my value"}'`. Can not edit ;) – A.D. Jul 10 '15 at 06:41
  • Any idea of getting this kind of object ? ` { "year": 2019, "month": 2, "day": 26 }` instead of { year: "2019", month: "2", day: "26" } – Denuka Feb 11 '19 at 10:45
  • 1
    @DenukaNirmalee Not sure what you mean, but you can use a replacer function, something like `JSON.stringify({ "year": "2019", "month": "2", "day": "26" }, (key, value) => !isNaN(+value) ? +value : value)` – KooiInc Feb 11 '19 at 13:53
  • Thank you so much Kooilnc and do you know how to how to remove all the double quotes in that object. That means getting an object like { year: 2019, month: 2, day: 26} – Denuka Feb 12 '19 at 04:11
  • @DenukaNirmalee Just surround the code with: `JSON.parse(...)` – KooiInc Feb 12 '19 at 06:35
6

This code

var jstr1 = {"mykey": "my value"};

creates a JavaScript object using the Object Literal Notation.
For the difference between the Object Literal Notation and JSON (JON is short for JavaScript object notation), see here: What is the difference between JSON and Object Literal Notation?

It makes logically no sense to pass this data to JSON.parse().

The difference to your first variant (var jstr = '{"mykey": "my value"}';) is that it creates a 'raw' string. You cannot access anything on that string except the raw character sequences. Using JSON.parse() gives us a usable form (object) created from the string.

SyntaxError: Unexpected token o

This comes from the automatic string conversion of jstr1:

jstr1.toString();
// gives us [object Object]
// ----------↑
Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156
6

You have some missunnderstanting for JSON.parse

JSON.parse takes string and parse it to JAVASCRIPT object
JSON.stringify takes an object and parse it to a string

thats why when you ran the following

JSON.parse('{"a":"b"}')

it worked because it expects a json string

but when you ran

JSON.parse({"a":"b"})

it didnt because the object was coverted to string which is

"[object Object]"

and here is the error where "[object Object]" is not valid syntax at letter o

Hilmi
  • 3,411
  • 6
  • 27
  • 55
2

JSON.parse() accepts a string and converts to JSON object, it doesnt take a javascript object as the parameter. Refer JSON.parse() It could give you the results as follows

JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null

and do know that If the string to parse is not valid JSON, a SyntaxError exception is thrown. so this is how you get syntax error on jstr1 (It is not a JSON string)

Ayyappan Sekar
  • 11,007
  • 2
  • 18
  • 22
-9

How about this:

MarahJSONObject gtp = new MarahJSONObject()
    gtp.put("ecomm_prodid", "123")
    gtp.put("ecomm_pagetype", "cart")
    gtp.put("ecomm_totalvalue", "19.99")

String r = gtp.toString()
    gtp.keySet().each {
        r = r.replace(/"${it}"/, it)
    }
    println r

then you will get: {ecomm_pagetype:"cart",ecomm_prodid:"123",ecomm_totalvalue:"19.99"}