Looks pretty simple but I am unable to figure it out
var str="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:\"11\"}]";
JSON.parse(str.replace(/\s/g, "").replace(/\//g, ''));
I am unable to the convert above string(which comes from 3rd party website) to valid json so that I can iterate it on my side
error
VM5304:1 Uncaught SyntaxError: Unexpected token n in JSON at position 2
at JSON.parse (<anonymous>)
JSON requires the keys to be quoted. It appears that your keys are coming in unquoted. So add another .replace statement to insert the quote back in:
.replace(/(\w+):/g, '"$1":');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Property names must be double-quoted strings; trailing commas are forbidden.
COMPLETE SOLUTION:
.replace(/(,|{)\s*(\w+)\s*:/g, '$1"$2":');
Related
In NodeJS Backend, I send my data to client as:-
res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) ))
//No error here and Object is stringified perfectly
//user is object returned in mongoDB's result
The JSON string looks like this:
{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0N31dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.yxQ1GrhLsWPn8Qwu42EfTDXqaYwFtrM6f_7cAH2eLRY"},"aboutme":"I am Rishav Bhowmik\r\nand this is navratna pulaow"}}
and that UID is just a mongodb's primary key as string, and other two base 64 strings are just JWT tokens.
Now, when this JSON string reaches the Browser, I parse it with simple:
JSON.parse(`<userdata>`)
//remember I used filex.replace("<userdata>", JSON.stringify...) in the server
For reference, my MongoDB Document here is:
Now when JSON.parse is executed on the JSON string it will look like this on final JS code.
JSON.parse(`{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0N31dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.yxQ1GrhLsWPn8Qwu42EfTDXqaYwFtrM6f_7cAH2eLRY"},"aboutme":"I am Rishav Bhowmik\r\nand this is navratna pulaow"}}`)
I get this error:
Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 1 column 702 of the JSON data
the string at position 702 of the JSON string is \n
First of all, how can \n be a control character?
What should I do to resolve this?
Has this problem arrised due to MONGODB result?
\n is a control character signifying a new line. In JSON, those control characters (more specifically the \) must be escaped inside strings.
This will raise the error:
JSON.parse(`{"hello":"world\n"}`)
This wont:
JSON.parse(`{"hello":"world\\n"}`)
So one way would be to use something like replace to ensure your aboutme is properly escaped before JSON serialization. See: How to escape a JSON string containing newline characters using JavaScript?
Ok have done some experimentation and have a solution.
The Trick is to do JSON.stringify() twice,
Like,
html_text.replace('/*<whatever>*/', JSON.stringify( JSON.stringify(the_object) ) )
If suppose html_text has a line which is
<script>
const object_inbrowser = JSON.parse(/*<whatever>*/)
// no need to add qotes, `JSON.stringify` in the server will do that for you
</script>
When I try to JSON.parse("foo"), I get an Error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at <anonymous>:1:6
But, when I use JSON.parse('"foo"'), I can get the result as expected:
const value = JSON.parse('"foo"');
console.log(value)
So why does this happen?
You can find what makes valid JSON at json.org. JSON can represent null, booleans, numbers, strings, arrays and objects. For strings, they must be enclosed in double quotes.
JSON itself is a string format, so when you specify a string in JSON format, you need:
quotes to tell JavaScript you are specifying a string literal. Those quotes are not part of the string value itself; they are just delimiters.
double-quotes inside that string literal to follow the JSON syntax for the string data type.
So here are some examples of correct arguments for JSON.parse:
JSON.parse("true")
JSON.parse("false")
JSON.parse("null")
JSON.parse("42")
JSON.parse("[13]")
JSON.parse('"hello"')
JSON.parse('{"name": "Mary"}')
But not:
JSON.parse("yes")
JSON.parse("no")
JSON.parse("none")
JSON.parse('hello')
JSON.parse({"name": "Mary"})
Because the argument will be cast to string when it is not, the following will also work, but it is confusing (and useless):
JSON.parse(true)
JSON.parse(false)
JSON.parse(null)
JSON.parse(42)
This happens because JSON.parse() gives a value back by formatting the string given using the syntaxis to declare values in Javascript. Therefore using foo naked would be like casting an undefined variable.
Notice also that the notation uses double quotes " instead of single ones '. That's why JSON.parse('"foo"') works but JSON.parse("'foo'") won't.
I am having problem converting a JSON String into Javascript object.
I ran into a few suggestions which said that I should not be using multi-line string but using single line string too did not work.
Snippet: https://jsfiddle.net/ankschoubey/hjh2d3z6/
SyntaxError: Unexpected token F in JSON at position 4536
Because you're including JSON as a JavaScript string value, you'll have to double-up on all the embedded backslash characters because they'll be parsed twice: first when the JavaScript parser reads the overall string constant to create the string value, and then again when you call JSON.parse().
Thus that portion of the string with \" should be \\". That way, the JavaScript string parsing will turn \\" into just \", and that's what will make the JSON parser happy.
I have the Json data , which I am trying to parse in the following fiddle
but its throwing error
Uncaught SyntaxError: Unexpected token p in JSON at position 15
I am unable to paste the json here due to the large size kindly follow the fiddle
var varArray = JSON.parse(jsonData);
console.log(varArray);
Fiddle
https://jsfiddle.net/ffeLtaa6/
any suggestion ?
You have incorrectly wrapped parts of your JSON in quotes
[{"pricing":"{\"price\": ....
^
This shouldn't be here
...
.... \"standingCharge\": \"y\"}}"}]
^
This shouldn't be here
Alternatively, maybe you ARE supposed to have that part wrapped, but then you need to properly escape all backslashes within that part, i.e. \\ instead of just \.
In that case, when you do JSON.parse(jsonData) you would get objects (inside the array) that all have a single property, pricing, with a value that is itself a JSON string.
It looks like your JSON data has objects enclosed in quotations.
Take the error at position 15; The string up to that point as interpreted by parse() is:
[{"pricing":"{"
At this point your parse function is looking for a comma to continue with or end bracket to finish this object.
Now, if you skip down the string to position 3312, you'll see the character sequence }}"}. Those last two brackets match up the ones in the very beginning.
The format of your string should be [{"pricing":"{ ... }"}] if you want a string under "pricing", or [{"pricing":{" ... "}}] if you want the object representing that string.
Take a look at how the object you are JSON-ifying is being constructed, I get the feeling you may be doubling down somewhere on a stringify() function for the parent object members.
I had a the same error "Uncaught SyntaxError: Unexpected token P in JSON at position 0"
the code was working but this message was shown on console with status 200
in my case i managed to avoid the error message by changing the return type from String to Integer
like this:
//before
public String method(){
//code here
return "evrything went as expected";
}
//after
public Integer method(){
//code here
return 0;
}
I think this has something to do with the browser that is expecting to get integers, im gonna update this answer if i discover something else
So, I'm trying to parse some JSON in Javascript. This feels like it should work, but I'm getting an error. Here's the function call:
JSON.parse("{player: 'green', direction: 'north'}");
And here's the error
VM156:1 Uncaught SyntaxError: Unexpected token p in JSON at position 1
at Object.parse (native)
at <anonymous>:1:6
I'm trying this on an empty web page, no JS libraries are present.
The string, just executed as Javascript creates an object with the two expected attributes.
I've tried wrapping the keys in strings. That didn't parse.
The unexpected token appears to be whatever the first letter is.
What am I doing wrong, how can I parse this object?
That's not valid JSON.
Try this:
JSON.parse('{"player": "green", "direction": "north"}');
Note the double quotes " instead of single quotes ' and the quotes around the object keys.