- JSON Parse error: Unrecognized token ‘ Asked 3 years ago
- 1 Answer 1
- Not the answer you’re looking for? Browse other questions tagged json parsing or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Ошибка JSON.parse: Unexpected Token
- Комментарии ( 0 ):
- HttpMessageNotReadableException: JSON parse error: Unrecognized token ‘嬀崀’
- 3 Answers 3
- JSON Parse error: Unrecognized token’ Asked 2 years, 11 months ago
- 12 Answers 12
- JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0`
- 7 Answers 7
JSON Parse error: Unrecognized token ‘ Asked 3 years ago
I am getting this error (as per Safari’s Web inspector) but I cannot see why. Most reports of this error suggest that it is reading a HTML tag somewhere . but I cannot see it.
The third line of code dumps the responseText onto my webpage (into a DIV called ‘myConsole’). This shows what I believe to be standard JSON code . and contains no ‘ Follow
1 Answer 1
Thank you raghav710 🙂
The console log showed it . I had some comments at the top of the dataSource.php file which were being included in the echo.
Writing this to my web page . they were ignored and invisible . which means I could not see them, and could not see the difference between the two outputs; parsing the comments JSON caused the choke.
I have removed all of the comments at the top of my datasource.php and it work instantly.
Thank you again.
Not the answer you’re looking for? Browse other questions tagged json parsing or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.6.10.39473
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Ошибка JSON.parse: Unexpected Token
JSON.parse() выдает ошибку «неожиданный токен» для правильного JSON
При работе с JSON порой происходит нечто непонятное — хотя строка JSON вроде бы и правильная, метод JSON.parse, выдает ошибку “unexpected token”. Это связано с тем, что JSON.parse не может разобрать некоторые специальные символы, такие как \n, \t, \r и \f. Поэтому и бросается исключение.
Поэтому, чтобы данное исключение не бросалось, необходимо экранировать эти специальные символы, прежде чем передавать строку JSON в функцию JSON.parse.
Вот функция, которая берет строку JSON и экранирует специальные символы:
function escapeSpecialChars(jsonString) <
return jsonString.replace(/\n/g, «\\n»)
.replace(/\r/g, «\\r»)
.replace(/\t/g, «\\t»)
.replace(/\f/g, «\\f»);
>
Таким образом вы можете решить ошибку «unexpected token» при работе с JSON.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
Источник
HttpMessageNotReadableException: JSON parse error: Unrecognized token ‘嬀崀’
I am calling an endpoint via RestTemplate as follows:
I have verified that the JSON String in the entity object is valid by copying it and using it in a cURL request to the same endpoint without any error. The same headers and authorization token were used in this request too.
When I execute the POST, I get back the following error:
My accept and content-type headers are both set to application/json . From examining the output from cURL, I see that there are no Chinese characters in the response body.
The response headers are as follows:
When I make the request with the responseType set to String.class or Object.class , the response is Chinese characters:
I am expecting that this call should return an empty array [] .
When I change the requestJson String to one which should serve back a non-empty array, I get back hundreds of Chinese characters instead of just two.
How can I decode the response to get valid data like when I use cURL?
I’m not sure how this is related, but the bytecode for the chars in an empty array [] are 91 and 93, and the bytecode for the two Chinese characters is 0, 91, 0, 93.
3 Answers 3
Do not use UTF16. HTTP Spec says ASCII, and many use UTF8. The error points this out with charset=utf-16 in it. Try setting the encoding header on the request.
What you’re seeing, as you noted with the char codes, is exactly the result expected when using UTF16 because each char is 2 bytes.
It seems like the response from restTemplate is returned as a String of Chinese characters not an array. The first error you posted seems to indicate that the issue is with extracting the response into an Object[] . If the response from the restTemplate is actually a String, then that would explain the second error as well. The RestTemplate was expecting to parse an array but instead received the String 嬀崀 . That’s why changing the response type to String.class seems to work.
If you’re expecting a JSON array back from the api you’re calling, then I would double check the response from the api you’re calling. Otherwise, I would suggest using String.class instead.
Edited: It’s possible that the restTemplate is parsing the response using the utf-16 charset and the server is encoding the response using the utf-8 charset. Like you’ve posted in the description, those characters seem to have the same bytecode. Maybe changing the expected charset in the restTemplate to utf-8 will resolve your problem.
Источник
JSON Parse error: Unrecognized token’ Asked 2 years, 11 months ago
«JSON Parse error: Unrecognized token’ Follow
12 Answers 12
This Means you are getting Html response from the server probably a 404 or 500 error. Instead of response.json() use response.text() you will get the html in text.
You can try by adding the headers to your fetch api, as it posts your record to your url.
I am pretty sure all these answers are correct. From what I have seen, if you have properly set the request header with:
The Accept header will tell the server what data type we are sending. Content-Type tells the client of what the response data type will be.
You most likely had to change the format of the body because the server may not be setup to handle application/json data types. In this case if you have access to your server you can add it to a config file or in .htaccess. If you still get the error, then there is an error in the server’s json response.
If you haven’t used POSTMAN for API testing, go and grab it because it has helped me lots with debugging API’s.
Источник
JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0`
I’m writing my first application in Node.js. I am trying to read some data from a file where the data is stored in the JSON format.
I get this error:
SyntaxError: Unexpected token in JSON at position 0
at Object.parse (native)
Here is this part of the code:
Here is the console.log output (and I checked the .json file itself, it’s the same):
That seems to me like a correct JSON. Why does JSON.parse() fail then?
7 Answers 7
You have a strange char at the beginning of the file.
I would recommend:
JSON.parse() does not allow trailing commas. So, you need to get rid of it:
You can find more about it here.
It might be the BOM[1]. I have done a test by saving a file with content <"name":"test">with UTF-8 + BOM, and it generated the same error.
And based on a suggestion here [2], you can replace it or drop it before you call JSON.parse() .
You can also remove the first 3 bytes (for UTF-8) by using Buffer.slice() .
try it like this
its because of the BOM that needs an encoding to be set before reading the file. its been issued in nodejs respository in github
To further explain @Luillyfe’s answer:
Ah-ha! fs.readFileSync(«data.json») returns a Javascript object!
Edit: Below is incorrect. But summarizes what one might think at first!
I had through that was a string. So if the file was saved as UTF-8/ascii, it would probably not have an issue? The javascript object returned from readFileSync would convert to a string JSON.parse can parse? No need to call JSON.stringify?
I am using powershell to save the file. Which seems to save the file as UTF-16 (too busy right now to check). So I get «SyntaxError: Unexpected token � in JSON at position 0.»
However, JSON.stringify(fs.readFileSync(«data.json»)) correctly parses that returned file object into a string JSON can parse.
Clue for me is my json file contents looking like the below (after logging it to the console):
That doesn’t seem like something a file would load into a string.
Incorrect being (this does not crash. but instead converts the json file to jibberish!):
I can’t seem to find this anywhere. But makes sense!
Edit: Um. That object is just a buffer. Apologies for the above!
Note: I don’t currently have a need for this to be async yet. Add another answer if you can make this async!
Источник