Ошибка разбора json ответа error while parsing text

Hi I am getting a json object as this.

{"messages":["operator  will assit you"]}

I am getting SyntaxError: JSON.parse: unexpected character
I am using $.parseJSON(json);

I couldn’t identify any syntax error in this.

  • ajax
  • json

asked Jan 8, 2014 at 17:01

Arun's user avatar

ArunArun

3,7115 gold badges32 silver badges43 bronze badges

1

  • Seems a problem of encoding. The ¿name? of the operator isn’t show

    Jan 8, 2014 at 17:07

2 Answers

Pasting your code snippet would be helpful. I would guess you aren’t parsing the string you are parsing the already parsed out object. You need to do one of the following:

var json = {"messages":["operator  will assit you"]};

or

var json = '{"messages":["operator  will assit you"]}';
$.parseJSON(json);

answered Jan 8, 2014 at 17:07

Spencer's user avatar

SpencerSpencer

7095 silver badges12 bronze badges

1

  • Of course, if you already have the object, you wouldn’t want or need to call parseJSON.

    Jan 8, 2014 at 17:11

Chris Farmer was right. The object is already in parsed state.

i just used
object.messages
and it worked like charm

answered Jan 8, 2014 at 17:32

Arun's user avatar

ArunArun

3,7115 gold badges32 silver badges43 bronze badges

1

  • Be sure to mark correct answer and close question. You should add this information as an edit instead of an answer.

    Jan 8, 2014 at 17:36

Пишу серверо-клиентское приложение, запросы/ответы идут в JSON (люблю с ним работать :) ) , для парсинга ответа использую библиотеку Newtonsoft.Json так вот, например ответ сервера:

{
	"status": true,
	"location": "https://ru.wargaming.net/id/openid/?openid.assoc_handle=%7BHMAC-SHA1%7D%7B53c3b656%7D%7BdbdXfQ%3D%3D%7D&openid.ax.if_available=ext0%2Cext1%2Cext2&openid.ax.mode=fetch_request&openid.ax.type.ext0=http%3A%2F%2Faxschema.openid.wargaming.net%2Fspa%2Fid&openid.ax.type.ext1=http%3A%2F%2Faxschema.org%2FnamePerson%2Ffriendly&openid.ax.type.ext2=http%3A%2F%2Faxschema.openid.wargaming.net%2Fidentity%2Fsso%2Fnotifications%2Fdisable&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.realm=https%3A%2F%2Fapi.worldoftanks.ru%2F&openid.return_to=https%3A%2F%2Fapi.worldoftanks.ru%2Fid%2Fcomplete%2F%3Fredirect_uri%3Dhttps%253A%252F%252Fapi.worldoftanks.ru%252Fwot%252Fblank%252F%26application_id%3D0775c3d2e437b4d3a2e386036571e297%26expires_at%3D1407221921%26janrain_nonce%3D2014-07-22T06%253A58%253A41ZepFnu1\"}d/openid/?openid.assoc_handle=%7BHMAC-SHA1%7D%7B53c3b656%7D%7BdbdXfQ%3D%3D%7D&openid.ax.if_available=ext0%2Cext1%2Cext2&openid.ax.mode=fetch_request&openid.ax.type.ext0=http%3A%2F%2Faxschema.openid.wargaming.net%2Fspa%2Fid&openid.ax.type.ext1=http%3A%2F%2Faxschema.org%2FnamePerson%2Ffriendly&openid.ax.type.ext2=http%3A%2F%2Faxschema.openid.wargaming.net%2Fidentity%2Fsso%2Fnotifications%2Fdisable&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.realm=https%3A%2F%2Fapi.worldoftanks.ru%2F&openid.return_to=https%3A%2F%2Fapi.worldoftanks.ru%2Fid%2Fcomplete%2F%3Fredirect_uri%3Dhttps%253A%252F%252Fapi.worldoftanks.ru%252Fwot%252Fblank%252F%26application_id%3D0775c3d2e437b4d3a2e386036571e297%26expires_at%3D1407221921%26janrain_nonce%3D2014-07-22T06%253A58%253A41ZepFnu1\"}d/openid/?openid.assoc_handle=%7BHMAC-SHA1%7D%7B53c3b656%7D%7BdbdXfQ%3D%3D%7D&openid.ax.if_available=ext0%2Cext1%2Cext2&openid.ax.mode=fetch_request&openid.ax.type.ext0=http%3A%2F%2Faxschema.openid.wargaming.net%2Fspa%2Fid&openid.ax.type.ext1=http%3A%2F%2Faxschema.org%2FnamePerson%2Ffriendly&openid.ax.type.ext2=http%3A%2F%2Faxschema.openid.wargaming.net%2Fidentity%2Fsso%2Fnotifications%2Fdisable&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.realm=https%3A%2F%2Fapi.worldoftanks.ru%2F&openid.return_to=https%3A%2F%2Fapi.worldoftanks.ru%2Fid%2Fcomplete%2F%3Fredirect_uri%3Dhttps%253A%252F%252Fapi.worldoftanks.ru%252Fwot%252Fblank%252F%26application_id%3D0775c3d2e437b4d3a2e386036571e297%26expires_at%3D1407221921%2"
}

Для удобства чтения отформатировал.

Так вот, при парсинге JObject’ом (функция JObject.Parse(json)) у меня вылетает исключение:

Необработанное исключение типа "Newtonsoft.Json.JsonReaderException" произошло в Newtonsoft.Json.dll

Дополнительные сведения: Additional text encountered after finished reading JSON content: \. Path '', line 1, position 1175.

Причем такое происходит в любых ответах сервера (содержимое которых сильно отличается), изменяется только позиция и «<какой-то символ>.Path».

В чем проблема? Я уже всячески обрабатывал строку как на сервере так и на клиенте, толку 0.
Причем странность: Ту-же строку (прямо из клиента выводом перед парсингом брал) например Notepad++ с плагином JSON Viewer спокойно парсит.

P.s. И да, на сервере JSON строка собирается тем-же JObject’ом.

UPD. Я покопался дебаггером, и обнаружил:
86c44ccec730483988606175bae34b02.png
Откуда ответ забивается «\0»?

@mplm17

Describe the bug
Zabbix API cannot be accessed by v4.0.0-alpha4 plugin, while v3.12.2 and older versions could. When saving config of zabbix datasource, the following message appears:

Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.

Expected behavior
Datasource configuration should be saved correctly. From grafana server, the following command returns a normal response:
curl -k -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":[],"id":1}' https://zabbix/api_jsonrpc.php
returns:
{"jsonrpc":"2.0","result":"5.0.1","id":1}

Screenshots
Here is my datasource conf, which works properly in stable versions:

image
image

The error message that I get when I click on ‘Save & Test’ button:

image

Software versions

Grafana Zabbix Grafana-Zabbix Plugin
7.1.1 5.0.1 4.0.0-alpha4

@alexanderzobnin

Hi! Could you show grafana-server logs?

@mplm17

Hi,

Yes sure, here are some logs:

t=2020-07-27T14:38:10+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/5/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=214 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″
t=2020-07-27T14:38:10+0200 lvl=eror msg=»Zabbix authentication error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T14:38:10+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T14:38:10+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/5/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=180 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″
t=2020-07-27T14:44:35+0200 lvl=eror msg=»Zabbix authentication error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T14:44:35+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T14:44:35+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/5/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=136 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″
t=2020-07-27T15:02:21+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T15:02:21+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/1/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=132 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″
t=2020-07-27T15:02:21+0200 lvl=eror msg=»Zabbix authentication error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T15:02:21+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T15:02:21+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/1/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=124 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″
t=2020-07-27T15:02:25+0200 lvl=eror msg=»Zabbix authentication error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T15:02:25+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-27T15:02:25+0200 lvl=eror msg=»Request Completed» logger=context userId=13 orgId=1 uname=xyz method=POST path=/api/datasources/1/resources/zabbix-api status=500 remote_addr=x.x.x.x time_ms=116 size=132 referer=»https://grafana.x.x/dashboard/new?editPanel=2&orgId=1″

@th0rtz

@alexanderzobnin

Ok, thanks for the details, I’ll try to reproduce this.

@alexanderzobnin

Could you also enable debug logging in grafana and post logs? It’s interesting, what’s an api method returns error.

@th0rtz

I don’t have much info in the debug log

t=2020-07-28T14:32:38+0200 lvl=dbug msg=»Received command to update data source» logger=datasources url=https://zabbix.lan/api_jsonrpc.php
t=2020-07-28T14:32:38+0200 lvl=dbug msg=»Applying default URL parsing for this data source type» logger=datasource type=alexanderzobnin-zabbix-datasource url=https://zabbix.lan/api_jsonrpc.php
t=2020-07-28T14:32:39+0200 lvl=dbug msg=»Data source settings changed» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource id=9.000 name=Zabbix org=1.000
t=2020-07-28T14:32:39+0200 lvl=dbug msg=»Initializing data source» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource name=Zabbix org=1.000 id=9.000
t=2020-07-28T14:32:39+0200 lvl=dbug msg=»Invoke Zabbix API request» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource ds=Zabbix method=apiinfo.version
t=2020-07-28T14:32:39+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-28T14:32:39+0200 lvl=eror msg=»Request Completed» logger=context userId=3 orgId=1 uname=usergrafana method=POST path=/api/datasources/9/resources/zabbix-api status=500 remote_addr=»» time_ms=139 size=132 referer=https://grafana.lan/datasources/edit/9/
t=2020-07-28T14:32:39+0200 lvl=dbug msg=»Invoke Zabbix API request» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource ds=Zabbix method=apiinfo.version
t=2020-07-28T14:32:39+0200 lvl=eror msg=»Zabbix API request error» logger=plugins.backend pluginId=alexanderzobnin-zabbix-datasource error=»Parse error Invalid JSON. An error occurred on the server while parsing the JSON text.»
t=2020-07-28T14:32:39+0200 lvl=eror msg=»Request Completed» logger=context userId=3 orgId=1 uname=usergrafana method=POST path=/api/datasources/9/resources/zabbix-api status=500 remote_addr=»» time_ms=85 size=132 referer=https://grafana.lan/datasources/edit/9/

@th0rtz

@mplm17

Hi,

Here is the post datas:
image

And the response:
image

@alexanderzobnin

I’ve got managed to replicate this in some cases, but still not sure why that happens. Give me a bit more time to figure it out.

@alexanderzobnin

Do you have any proxy behind your Zabbix? I see this if I query zabbix.org:

# curl -k -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":10}' http://www.zabbix.org/zabbix/api_jsonrpc.php
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://zabbix.org/zabbix/api_jsonrpc.php">here</a>.</p>
<hr>
<address>Apache/2.2.29 (Linux/SUSE) Server at www.zabbix.org Port 80</address>
</body></html>

If I add -L flag to follow redirects, then I get the same error:

# curl -k -L -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":10}' http://www.zabbix.org/zabbix/api_jsonrpc.php
{"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request.","data":"The received JSON is not a valid JSON-RPC Request."},"id":null}

But if I query https://zabbix.org/zabbix/api_jsonrpc.php directly, it works:

# curl -k -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":2}' https://zabbix.org/zabbix/api_jsonrpc.php
{"jsonrpc":"2.0","result":"4.2.0","id":2}

So it looks like proxy redirects query with changes that leads to wrong request.

@mplm17

Hi,

No, I don’t have any proxy behind zabbix.

I’ve tried the same command as yours from grafana server, with the same url setted in datasource configuration:

curl -k -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"apiinfo.version","params":{},"id":10}' https://zabbix.mydomain/api_jsonrpc.php

And it works:

{"jsonrpc":"2.0","result":"5.0.1","id":10}

@alexanderzobnin

That’s strange. Could you check it against a different Zabbix server?

@mplm17

With zabbix.org it seems working:

image

image

So the problem is related to my zabbix server? I will upgrade to 5.0.3, maybe this is a bug in 5.0.1…

@mplm17

Same issue after upgrading in 5.0.3…

@th0rtz

My zabbix server is on 4.2.6 and i have the same issue.

@alexanderzobnin

What’s an OS you’re running Grafana on, BTW?

@alexanderzobnin

Also, it might be related to SSL, so try to set Skip TLS Verify option.

@alexanderzobnin

@mplm17

My Grafana is running on CentOS 7.8.

Same error when enabling Skip TLS Verify option. But btw, this option doesn’t seem to work, cause if I change the url by setting the IP instead of domain name, it returns the following error even if Skip TLS Verify option is enabled…

Post https://192.168.x.y/api_jsonrpc.php: x509: cannot validate certificate for 192.168.x.y because it doesn't contain any IP SANs

Same error if I put an other domain name (which is an alias of the long DN):

Post https://zabbix/api_jsonrpc.php: x509: certificate is valid for zabbix.mydomain, not zabbix

So it seems like Skip TLS Verify option is ignored

@mplm17

I’m currently going further into debugging. I found a way to log every requests on zabbix api. I can see that requests coming from grafana to zabbix api have no data:

POST
ACCEPT-ENCODING: gzip
CONTENT-TYPE: application/json
TRANSFER-ENCODING: chunked
USER-AGENT: Go-http-client/1.1
HOST: zabbix.mydomain


while requests that come from another app have datas:

POST
CONTENT-LENGTH: 277
CONTENT-TYPE: application/json
ACCEPT: */*
HOST: zabbix.mydomain

{"jsonrpc":"2.0","method":"trigger.get","params":{"monitored":true,"only_true":1,"min_severity":1,"sortfield":["lastchange"],"sortorder":"DESC","withLastEventUnacknowledged":true,"expandDescription":true,"selectHosts":["name"]},"id":1,"auth":"***"}

Headers are also not the same… Maybe this could help?

Edit: I upgraded the plugin in 4.0.0 (latest).

@alexanderzobnin

That looks strange. Maybe it’s related to the go-http-client. I’ll check it out as well.

@Shmakovm

Same issue after upgrading in 4.0.0, zabbix 5.0.3 and grafana 7.1.5 (Centos 7.8). On version 3.12.3, there was no error.

@alexanderzobnin

@Shmakovm

@Shmakovm do you use https on Zabbix server?

Yes, I use https with an internal CA certificate.
It’s the same thing I used with the 3.12.3 plugin version and everything worked.

@alexanderzobnin

@Shmakovm did you use Skip TLS Verify option with 3.12? I found it doesn’t work with 4.0 because I have to implement it at the backend side.

@Prefix

Tested with few Zabbix instances.
1st instance v4 Zabbix (no proxy, no ssl) — Works on Grafana
2nd instance v5 Zabbix troublesome (has Zabbix proxy but it’s unrelated to frontend, with proper SSL wildcard certificate (bought one)) — Errors like for everyone
3rd one is Zabbix Appliance v5 straight from Zabbix website, no SSL there is no issues. — Works on Grafana

I tried non-working one with HTTP protocol as well (turned off https, seem that didn’t fixed the issue).
SSL certificate is properly configurated (public key contains root public certificates as well)
Skip TLS Verify doesn’t help to fix the issue.

Also I checked Zabbix logs it said 200 HTTP codes (httpd logs), not 500 like grafana website says (chrome developer javascript errors).

@Prefix

@alexanderzobnin

Yes, looks like it’s not related to the SSL cert verification. I tried to test it against Zabbix 5.0.2 from official docker container and added self-signed cert. I get this error when testing data source:

Post "https://localhost:8189/api_jsonrpc.php": x509: certificate signed by unknown authority

If I add InsecureSkipVerify to the http client config, then it works.

So since it works with 3.12 (where grafana send the query), but doesn’t work with 4.0 (where plugin backend sends request), there should be some difference between how grafana performs a query and how the plugin do the same.

But I still can’t replicate this bug to figure it out, so any details about your environment would be super helpful.

@Shmakovm

@Shmakovm did you use Skip TLS Verify option with 3.12? I found it doesn’t work with 4.0 because I have to implement it at the backend side.

No, I didn’t.

for example how curl works.

Annotation 2020-08-28 080841

@mplm17

How have you add the InsecureSkipVerify option? Maybe we could try the same?

Concerning my environment:

Grafana (7.1.5) is running on:
Centos 7.8
local CA is trusted

Zabbix (5.0.3) is running on:
Centos 7.8
httpd 2.4.6
HTTP certificate signed by a local CA

If you need any other info, just tell me ;)

@alexanderzobnin

@mplm17 I did it in the source code :) I will fix HTTP options support anyway. If someone can collect traces of HTTP requests that Grafana backend sends to Zabbix, it would be nice.

@Prefix

I tried v6.6.1 (21bf8b71bc) grafana it works fine. It says Zabbix API version: 5.0.3. Grafana Zabbix Plugin version 3.10.5
At least I’m quite sure it’s something wrong from plugin code side.

@achupahin

@alexanderzobnin

@achupahin that’s browser logs. But I need logs of requests that backend plugin sends. It’s not so easy to collect, you need something like tcpdump or wireshark.

@alexanderzobnin

@Prefix yes, it’s definitely plugin issue.

@mplm17

@achupahin that’s browser logs. But I need logs of requests that backend plugin sends. It’s not so easy to collect, you need something like tcpdump or wireshark.

I’m trying to do something like that, but it’s not easy due to the SSL layer…

@achupahin

@Nehemoth

@mplm17

@alexanderzobnin Here it is:

image

Here are 2 others examples that are working good, so we can see the differences:

-with postman:

image

-from another zabbix api client:

image

With these outputs, I tried to reproduce the problem on postman by setting the same headers that are set in grafana requests. It seems that if «Content-Length» header is set, it works properly, but if it’s not set, we have the parse error…

Hope this will help

@alexanderzobnin

@mplm17 yes, this super helpful, thanks a lot!

@alexanderzobnin

@alexanderzobnin

Ok, tried to solve it. Could anyone test it out and confirm that bug fixed? Here’s a built package for all platforms. Just unpack it into grafana plugins folder.

grafana-zabbix-8f70a0c.zip

@achupahin

@EdersonDeves

@mobarrio

Ok, tried to solve it. Could anyone test it out and confirm that bug fixed? Here’s a built package for all platforms. Just unpack it into grafana plugins folder.

grafana-zabbix-8f70a0c.zip

Work Zabbix 5.0.2 Grafana 7.1.5

@mplm17

Ok, tried to solve it. Could anyone test it out and confirm that bug fixed? Here’s a built package for all platforms. Just unpack it into grafana plugins folder.

grafana-zabbix-8f70a0c.zip

Thank you very much! It’s working for me too ;)

@alexanderzobnin

Ok, so closing this. Fix will be available in upcoming release soon.

Синтаксическая ошибка:JSON.parse:плохой парсинг

Исключения JavaScript, создаваемые JSON.parse() возникают, когда строку не удалось проанализировать как JSON.

Message

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or 
SyntaxError: JSON.parse: end of data when 
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when 
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or 
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

Error type

Что пошло не так?

JSON.parse() анализирует строку как JSON. Эта строка должна быть действительным JSON и вызовет эту ошибку, если будет обнаружен неправильный синтаксис.

Examples

JSON.parse()не позволяет использовать запятые в конце текста

Обе линии бросят синтаксическую ошибку:

JSON.parse('[1, 2, 3, 4,]');
JSON.parse('{"foo": 1,}');


Опустите запятые,чтобы правильно разобрать JSON:

JSON.parse('[1, 2, 3, 4]');
JSON.parse('{"foo": 1}');

Имена объектов недвижимости должны быть двузначно процитированными.

Нельзя использовать одиночные кавычки вокруг свойств,например,’foo’.

JSON.parse("{'foo': 1}");


Вместо этого напишите «фу»:

JSON.parse('{"foo": 1}');

Ведущие нули и десятичные знаки

Нельзя использовать опережающие нули,например 01,а за десятичными точками должен следовать хотя бы один знак.

JSON.parse('{"foo": 01}');



JSON.parse('{"foo": 1.}');


Вместо этого запишите только 1 без нуля и используйте по крайней мере одну цифру после запятой:

JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');

See also

  • JSON
  • JSON.parse()
  • JSON.stringify()


JavaScript

  • TypeError: недопустимый операнд «экземпляр» «х»

    Исключение JavaScript «недопустимый операнд экземпляра» возникает, когда оператор правых операндов не используется с объектом конструктора, т.е.

  • TypeError: ‘x’ не повторяется

    Исключение JavaScript «не является итерируемым» возникает, когда значение, заданное правой частью for…of, функции аргумента, такой как Promise.all TypedArray.from,

  • Синтаксическая ошибка:Некорректный формальный параметр

    Исключение JavaScript «искаженный формальный параметр» возникает, когда список аргументов вызова конструктора Function() каким-то образом недействителен.

  • URIError:некорректная последовательность URI

    Исключение JavaScript «неверная последовательность URI» возникает, когда декодирование кодирования не было успешным.

JSON, or JavaScript Object Notation, is a ubiquitous data format used by all sorts of mobile and web apps for asynchronous browser-server communication. JSON is an extremely popular data format, very easy to work with, compatible with every major programming language, and is supported by every major browser. However, just like any programming language, it throws a lot of errors when it decides that today is not going to be your day.

JSON.Parse Syntax Errors

In most web applications, nearly all data transferred from a web server is transmitted in a string format. To convert that string into JSON, we use the JSON.parse() function, and this is the main function that throws errors. Nearly all JSON.parse errors are a subset of the SyntaxError error type. The debugging console throws around 32 different error messages when you mess up your JSON data. And some of them are very tricky to debug; and yes I am talking about you unexpected non-whitespace character after JSON data.

Why the SyntaxError Horror?

SyntaxError is an inherited object of the main error object The main reason behind the error is usually a mistake in the JSON file syntax. You mess up and put a “ instead of a ‘ and you invite to face the SyntaxError JSON.parse: unexpected character.

Just like every programming language, a JSON file has a fixed syntax. Small syntax errors throws errors. For example, in the following code, I forgot to remove a trailing comma

JSON.parse('[a,b, c, d, e, f,]');

Error1

Similarly, in this example, I forgot to add the final } character.

JSON.parse('{"LambdaTest": 1,');

error2

How to Catch the Error Before Hand

The problem with debugging JSON errors is that you only get to know about one error at a time. Debuggers throw the first error they find and then stop. It would be up to you to regression find the bugs. Usually, it’s not as difficult as it sounds.

The first step is to make sure that your JSON file is perfect from the get go. Here you can take help from JSON linting tools like cleverly named jsonlint.com

If you don’t have any control over the receiving JSON file, then the next step is to add catch exceptions around your JSON.parse.

function validatingJSON (json) {

  var checkedjson

  try {
    checkedjson = JSON.parse(json)
  } catch (e) {

  }

  return checkedjson }

Also, here are the main errors related to JSON.parse that I very painstakingly collected from a very single source [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse]:

SyntaxError: JSON.parse: unterminated string literal 
SyntaxError: JSON.parse: bad control character in string literal 
SyntaxError: JSON.parse: bad character in string literal 
SyntaxError: JSON.parse: bad Unicode escape 
SyntaxError: JSON.parse: bad escape character 
SyntaxError: JSON.parse: unterminated string 
SyntaxError: JSON.parse: no number after minus sign 
SyntaxError: JSON.parse: unexpected non-digit 
SyntaxError: JSON.parse: missing digits after decimal point 
SyntaxError: JSON.parse: unterminated fractional number 
SyntaxError: JSON.parse: missing digits after exponent indicator 
SyntaxError: JSON.parse: missing digits after exponent sign 
SyntaxError: JSON.parse: exponent part is missing a number 
SyntaxError: JSON.parse: unexpected end of data 
SyntaxError: JSON.parse: unexpected keyword 
SyntaxError: JSON.parse: unexpected character 
SyntaxError: JSON.parse: end of data while reading object contents 
SyntaxError: JSON.parse: expected property name or '}' 
SyntaxError: JSON.parse: end of data when ',' or ']' was expected 
SyntaxError: JSON.parse: expected ',' or ']' after array element 
SyntaxError: JSON.parse: end of data when property name was expected 
SyntaxError: JSON.parse: expected double-quoted property name 
SyntaxError: JSON.parse: end of data after property name when ':' was expected 
SyntaxError: JSON.parse: expected ':' after property name in object 
SyntaxError: JSON.parse: end of data after property value in object 
SyntaxError: JSON.parse: expected ',' or '}' after property value in object 
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal 
SyntaxError: JSON.parse: property names must be double-quoted strings 
SyntaxError: JSON.parse: expected property name or '}' 
SyntaxError: JSON.parse: unexpected character 
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

If this doesn’t help, then you are in for one long debugging session.

Понравилась статья? Поделить с друзьями:
  • Ошибка разблокировки nox app player
  • Ошибка разбора css валидатор
  • Ошибка разбор слова под цифрой 2
  • Ошибка разбор xml
  • Ошибка разблокировки загрузчика xiaomi 1004