I have a json from my server which is -
{"canApprove": true,"hasDisplayed": false}
I can parse the json like this -
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject
-
//response function
function(jsonObject){
//here jsonObject contains the same json - {"canApprove":true,"hasDisplayed": false}
//But without the surrounding single quote
//I have confirmed about this by seeing my server side log.
var msg = JSON.parse(jsonObject); // this gives the error
}
But now I got the following error -
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Can anyone tell me why I am getting the error?
parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code. If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands.
The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).
Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:
the String is surround by " ". and use \" escape inside example:
"{\"name\":\"alan\",\"age\":34}"
when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \" is replace by ". But use the JSON.parse() again, it will return the object you want. So in this case,you can do this:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))
use ' instead of " . example:
{'name':'alan','age':34}
when you try to parse above string by JSON.parse(), may cause error
I dont think you should call JSON.parse(jsonObject)
if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/json
header it will be parsed automatically.
Try using jsonObject
as if it was already parsed, something like:
console.log(jsonObject.canApprove);
Without calling JSON.parse
before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With