why JSON.parse does not convert a string to json object? - javascript

I tried to convert a string to a javascript object using JSON.parse but it's not working.
I tried everything but did not get anything on the console.log and there is no error message.
JSON.parse(`{'exp': '1', 'input': '1d6404f66ed3d72e', 'iterate': 'no'}`);
Update
In the real code, I'm passing the value from an object
console.log(JSON.parse(future.onIOPub.data['text/plain']))

When you run this, you should see
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
This error is because you are using single quotes. JSON only accepts double quotes, as described in the spec
https://www.json.org/json-en.html

Related

Javascript - Unable to read json key values - Unexpected token i in JSON at position 1 - sql query output problem

I'ved got this string generated from sql query (basically using ARRAY_AGG and some cases to format the output) that looks like this
{id:2,name_of_division:'super department1',attendance_radius:1000}
However, in javascript, I cant get any of the key values and its also causing JSON parse error.
I'ved tried validating this JSON and it looks perfectly fine.
Here are some of the troubleshooting, I have no idea what is causing it
console.log(clean_div_array_var[i].toString());
output ==> {id:2,name_of_division:'super department1',attendance_radius:1000}
console.log("id:" + clean_div_array_var[i].id);
output ==> id:undefined
console.log("name_of_division:" + clean_div_array_var[i].name_of_division);
output ==> name_of_division:undefined
JSON.parse(clean_div_array_var[i]);
output ==>
VM2561:1 Uncaught SyntaxError: Unexpected token i in JSON at position 1
at JSON.parse (<anonymous>)
at get_all_key_of_div_array ((index):817)
at render ((index):2321)
at jquery.dataTables.min.js:18
at Object.b.fnGetData (jquery.dataTables.min.js:12)
at B (jquery.dataTables.min.js:17)
at Ha (jquery.dataTables.min.js:25)
at O (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:49
at i (jquery.dataTables.min.js:35)
I even try to stringify, then somehow remove quotes (I dont understand why this even appears) and then JSON parse. Same problem.
stringifyvar = JSON.stringify(clean_div_array_var[i])
output ==> "{id:2,name_of_division:'super department1',attendance_radius:1000}"
stringifyvar = stringifyvar.split('\"').join('');
console.log("stringify remove quote:" + stringifyvar);
output ==> stringify remove quote:{id:2,name_of_division:'super department1',attendance_radius:1000}
parsed_json_data = JSON.parse(stringifyvar);
output ==>
VM2503:1 Uncaught SyntaxError: Unexpected token i in JSON at position 1
at JSON.parse (<anonymous>)
at get_all_key_of_div_array ((index):816)
at render ((index):2320)
at jquery.dataTables.min.js:18
at Object.b.fnGetData (jquery.dataTables.min.js:12)
at B (jquery.dataTables.min.js:17)
at Ha (jquery.dataTables.min.js:25)
at O (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:49
at i (jquery.dataTables.min.js:35)
How can I read any of the keys properly from this json
Your result is not valid JSON. Valid format would be:
{"id":2, "name_of_division":"super department1", "attendance_radius":1000}
The keys have to be quoted, and the quotes around the string super department1 have to be double quotes, not singlequotes.
You need to generate proper JSON if you want to be able to use JSON.parse() to process it.

Error with JSON.parse() of stringified array from sessionStorage

I need to store an array in sessionStorage and found this answer helpful: Storing Objects in HTML5 localStorage
Storing the array with sessionStorage.setItem('flavors', JSON.stringify(flavors)) and retrieving the string with JSON.parse(sessionStorage.getItem('flavors')) works the first time. Then, testing this plain-JavaScript PWA with the back- and forward- buttons, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Depending on the elements of the array, the column number can vary.
I can avoid the error by using:
flavors = sessionStorage.getItem('flavors').split(",");
instead of JSON.parse(). Along with the error, I can console log the string which looks okay:
chocolate,vanilla,strawberry
What could be causing the error?
In order to parse JSON, the string must represent a valid JSON, in you case this JSON.parse('["chocolate","vanilla","strawberry"]') will work

JSON.parse() fail to parse a String with a JSON Object inside

I have a JSON Object which contains the following structure:
{"msg":"text","id":integer}
The user enters the text and the object is generated in the server-side (Java) and then passed as a String to JSON.parse() on the client-side.
The problem is, when a user enters a JSON Object format as the text, the function fails with:
SyntaxError: Unexpected token E in JSON at position 1
The string that resulted this error is:
{"msg":"{ENABLE:0,MOVING:0,ERRMESSAGE:}","id":999}
Any ideas for a workaround? I don't understand why it's failing.

JSON Parse with square brackets inside data

I am trying to parse a JSON string which contains square brackets inside the string.
For example
"[[\"hello\", \"i\", \"like [cows]\"], [\"what\", \"about [you]?\"]]"
It shows an error while parsing:
Uncaught SyntaxError: Unexpected token [
How can I parse the string anyway while leaving the brackets as they are?
I found the problem. I needed to use addslashes() around the strings in the PHP code which serves the code. There was a part of a string containing [C:\].
I see in your later comments that you're creating this JSON string within PHP. You should encode the JSON data within PHP using json_encode, as shown here:
http://www.dyn-web.com/tutorials/php-js/json/array.php
It should then come out in a format that you can JSON.parse.

JSON: Error while Parsing

I've the following JSON(Valid) sting.
[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]
it gives error when I try to Parse using the JSON.parse function
here is the code that I'm using for parsing.
JSON.parse('[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]');
and it gives an error in console Uncaught SyntaxError: Unexpected token i
here is the Correct Output by same string using online JSON viewer.
When you use JSON viewer, it's different from when you use the code in your JS code. Like #Jonathan stated, you should double escape you json sting.
JSON.parse('[["abc","{\\"icon\\":\\"adjust\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"red\\"}"],["xyz","{\\"icon\\":\\"archive\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"green\\"}"],["azs","{\\"icon\\":\\"asterisk\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"darkred\\"}"]]');
Your json structure is invalid. You should use this instead(without slashes):
'[["abc",["icon":"adjust","prefix":"fa","markerColor":"red"]],["xyz",["icon":"archive","prefix":"fa","markerColor":"green"]],["azs",["icon":"asterisk","prefix":"fa","markerColor":"darkred"]]'

Categories

Resources