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
Related
I think this is a basic question, but I can't understand the reason. in JSON, it's valid to has a special character like "asdfadf\tadfadf", but when try parse it, it's shown error.
eg. code:
let s = '{"adf":"asdf\tasdfdaf"}';
JSON.parse(s);
Error:
Uncaught SyntaxError: Bad control character in string literal in JSON at position 12
at JSON.parse (<anonymous>)
at <anonymous>:1:6
I need to understand what is the issue, and solution.
You have to take into account that \t will be involved in two parsing operations: first, when your string constant is parsed by JavaScript, and second, when you parse the JSON string with JSON.parse(). Thus you must use
let s = '{"adf":"asdf\\tasdfdaf"}';
If you don't, you'll get the error you're seeing from the actual tab character embedded in the string. JSON does not allow "control" characters to be embedded in strings.
Also, if the actual JSON content is being created in server-side code somehow, it's probably easier to skip building a string that you're immediately going to parse as JSON. Instead, have your code build a JavaScript object initializer directly:
let s = { "adf": "asdf\tasdfdaf" };
In your server environment there is likely to be a JSON tool that will allow you to take a data structure from PHP or Java or whatever and transform that to JSON, which will also work as JavaScript syntax.
let t = '{"adf":"asdf\\tasdfdaf"}';
var obj = JSON.parse(t)
console.log(obj)
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>
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":');
I've an encoded stringifyed JSON object stored in database, I decoded it and loaded it and tried to parse it into an object But I get
Uncaught SyntaxError: Unexpected token ' in JSON at position 2
at JSON.parse ()
Code:
var attr = new Object();
attr = JSON.parse(code[1].replace(/"/g, "'"));
Object decoded:
[{'inputs':0,'type':'variable'},{'inputD':0,'type':'variable'},{'inputI':0,'type':'variable'},{'paras':0,'type':'variable'},{'headers':0,'type':'variable'},{'menus':0,'type':'variable'},{'lists':0,'type':'variable'},{'divs':0,'type':'variable'},{'links':0,'type':'variable'},{'images':0,'type':'variable'},{'elemName':'{}','type':'object'},{'borders':[],'type':'array'},{'nested':[],'type':'array'},{'ribbons':[],'type':'array'},{'tooltips':[],'type':'array'},{'gradColors':'{}','type':'object'},{'events':'{}','type':'object'},{'sTarget':'{}','type':'object'},{'sMain':'{}','type':'object'},{'orignalStyle':'{}','type':'object'},{'objNewStyle':'{}','type':'object'},{'functions':'{}','type':'object'},{'reverse':'{}','type':'object'},{'reverseFunction':'{}','type':'object'},{'scDetails':'{}','type':'object'}]
I have same error, #Philipp Zitzmann is correct.
You must valid json string at https://jsonformatter.curiousconcept.com/
valid json string must have double quote.
JSON.parse({"u1":1000,"u2":1100}) // will be ok
no quote cause error
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
single quote cause error
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
JSON should be wrapped in double quotes like:
{"inputs":0,"type":"variable"}
This is a useful Tool for validating:
https://jsonformatter.curiousconcept.com/
This is not valid json string. Its values and keys should be surrounded with double quotes (not single). So when you do .replace(/"/g, "'") you basically break the JSON standard.
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
A related one. Today I hit the same error. An example is below:
Correct
JSON.parse( "[1,2,3,4,5,6,7,8,9,0]" )
Incorrect
JSON.parse( "[1,2,3,4,5,6,7,8,..." )
Note the 3 dots (...), because a tool showed only few numbers in array, and gave ... for rest.
In other words, string passed to JSON.parse() is invalid, so it gave error.
But it can be any other similar error.
For example, (may be) JSON.parse( "true" ) is correct but JSON.parse( "tr" ) fails, etc.
I am Trying to retrieve data from json in my code. Json data doesn't contain any brackets. It is just any array separated by commas(,). My Problem is that when I get data using $scope, an extra sqaure bracket get added outside my output. Demo of my code is
controller.js
$http.get("serverUrl")
.success(function(data) {
$scope.sour = data;
})
.error(function(err) {
console.log("Error in source: "+JSON.stringify(err));
});
html
<div>
{{sour}}
</div
expected json
data
error
[data]
I have tried old stack solutions but none of them worked out for me.
Please share if anyone know why this error being produced, As I have used this method a hundred times before but never faced this problem.Regards.
After trying found out a solution.
.toString().replace();
solved out my problem.
As per how JSON.stringify should work as specified here, the result that you explained is as expected.
Let separator be the result of concatenating the comma character,
the line feed character, and indent.
Let properties be a String
formed by concatenating all the element Strings of partial with each
adjacent pair of Strings separated with separator. The separator
String is not inserted either before the first String or after the
last String.
Let final be the result of concatenating "[", the line
feed character, indent, properties, the line feed character,
stepback, and "]"
Which will result in a valid JSON String. The format you are requesting is confusing and is probably an invalid JSON. You can try checking the JSON using some JSON validator online. (Notice that [1,2,3,4] is valid where as 1,2,3,4 is invalid)
You are probably having a service that is expecting a malformed JSON, it will be better to fix that part instead of duck taping your JSON.
Meanwhile, the only thing you are explaining is the format you are getting and the format that is working. You haven't still specified where exactly the error happens? Is it error from HTTP request? Is it error thrown in Javascript? What is causing the error? What error messages are you getting?