here is the structure of json which is coming valid on jsonlint. I just need to fetch the first block all details like hostid and all. I tried to parse the data but getting one error.
{
"u0000yii\db\BaseActiveRecordu0000_attributes": {
"hostid": 234,
"user_id": 77,
"hometype": "house",
"roomtype": "Entire Home",
"accommodates": "2",
"city": "Chandigarh",
"street_address": "",
"state": "Chandigarh 160017",
"zipcode": "",
"country": "India",
"latitude": "30.740212629732113",
"longitude": "76.78718557730713",
"address": "Bank Square, 17C, Sector 17, Chandigarh, Chandigarh 160017, India",
"bedrooms": "2",
"beds": "2",
"bathrooms": "1",
"from_date": "2015-07-16",
"to_date": "2015-08-19",
"available": "",
"amount_pernight": 100,
"currency": "INR",
"title": "AmazingSeaFacingPrivateRoom",
"summery": "Title should highlight the key features and will attract guests to choose your listing! Add an innovative title that best describes your home.rnrnExamples:rnrn Amazing Sea Facing Private Room!rn Fully Furnished Villa!rn Free Welcome Drink on Arrival!rn",
"mostcomman_facilities": "New Soap & Shampoo Sachet-:-Dry-cleaned Towel-:-Blanket-:-TV-:-Cable TV-:--:--:--:--:--:-",
"extra_facilities": "Extra Mattress-:-Extra Blanket-:-Washer-:-Alarm clock-:-Laundry Service-:-Gym-:--:--:--:--:-",
"features_facilities": "Smoking Allowed-:-Family & Children Friendly-:-Pets allowed-:-Wheelchair Available",
"safety_facilities": "Fire Extinguisher-:-Smoke Detector-:-Carbon Monoxide Detector-:-",
"num_bed": "0",
"bed_type": 2,
"currency_symbol": "",
"servicefee": "",
"cleaningfee": "",
"person": "all",
"landmark_location": "",
"landmark_distance": "",
"hostuniqueweb": "",
"hosttype": "web",
"extraperson": "Free",
"breakfast": "Free",
"Lunch": "Free",
"Dinner": "Free",
"Tea": "Free",
"Coffee": "Free",
"Airport": "Free"
},
"u0000yii\db\BaseActiveRecordu0000_oldAttributes": {
"hostid": 234,
"user_id": 77,
"hometype": "house",
"roomtype": "Entire Home",
"accommodates": "2",
"city": "Chandigarh",
"street_address": "",
"state": "Chandigarh 160017",
"zipcode": "",
"country": "India",
"latitude": "30.740212629732113",
"longitude": "76.78718557730713",
"address": "Bank Square, 17C, Sector 17, Chandigarh, Chandigarh 160017, India",
"bedrooms": "2",
"beds": "2",
"bathrooms": "1",
"from_date": "2015-07-16",
"to_date": "2015-08-19",
"available": "",
"amount_pernight": 100,
"currency": "INR",
"title": "AmazingSeaFacingPrivateRoom",
"summery": "Title should highlight the key features and will attract guests to choose your listing! Add an innovative title that best describes your home.rnrnExamples:rnrn Amazing Sea Facing Private Room!rn Fully Furnished Villa!rn Free Welcome Drink on Arrival!rn",
"mostcomman_facilities": "New Soap & Shampoo Sachet-:-Dry-cleaned Towel-:-Blanket-:-TV-:-Cable TV-:--:--:--:--:--:-",
"extra_facilities": "Extra Mattress-:-Extra Blanket-:-Washer-:-Alarm clock-:-Laundry Service-:-Gym-:--:--:--:--:-",
"features_facilities": "Smoking Allowed-:-Family & Children Friendly-:-Pets allowed-:-Wheelchair Available",
"safety_facilities": "Fire Extinguisher-:-Smoke Detector-:-Carbon Monoxide Detector-:-",
"num_bed": "0",
"bed_type": 2,
"currency_symbol": "",
"servicefee": "",
"cleaningfee": "",
"person": "all",
"landmark_location": "",
"landmark_distance": "",
"hostuniqueweb": "",
"hosttype": "web",
"extraperson": "Free",
"breakfast": "Free",
"Lunch": "Free",
"Dinner": "Free",
"Tea": "Free",
"Coffee": "Free",
"Airport": "Free"
},
"u0000yii\db\BaseActiveRecordu0000_related": [],
"u0000yii\base\Modelu0000_errors": null,
"u0000yii\base\Modelu0000_validators": null,
"u0000yii\base\Modelu0000_scenario": "default",
"u0000yii\base\Componentu0000_events": [],
"u0000yii\base\Componentu0000_behaviors": []
}
And here is my code for parsing this structure :
JSONObject obj = new JSONObject(jsonStr);
System.out.println("hello");
JSONObject ob=obj.getJSONObject("u0000yii\db\BaseActiveRecordu0000_attributes");
System.out.println("hello123");
home_type=ob.getString("home_type");
Log.v("home type is", home_type);
I am getting the following error in logcat. Here is the logcat details. plz help :
07-13 16:21:07.868: W/System.err(4678): org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
07-13 16:21:07.868: W/System.err(4678): at org.json.JSON.typeMismatch(JSON.java:111)
07-13 16:21:07.869: W/System.err(4678): at org.json.JSONObject.<init>(JSONObject.java:159)
07-13 16:21:07.869: W/System.err(4678): at org.json.JSONObject.<init>(JSONObject.java:172)
07-13 16:21:07.869: W/System.err(4678): at com.app.hostguestapp.Preview_form$Preview_form_data.doInBackground(Preview_form.java:91)
07-13 16:21:07.869: W/System.err(4678): at com.app.hostguestapp.Preview_form$Preview_form_data.doInBackground(Preview_form.java:1)
07-13 16:21:07.869: W/System.err(4678): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-13 16:21:07.869: W/System.err(4678): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-13 16:21:07.870: W/System.err(4678): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-13 16:21:07.870: W/System.err(4678): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-13 16:21:07.870: W/System.err(4678): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
here is the structure of json which is coming valid on jsonlint. I just need to fetch the first block all details like hostid and all. I tried to parse the data but getting one error.
{
"u0000yii\db\BaseActiveRecordu0000_attributes": {
"hostid": 234,
"user_id": 77,
"hometype": "house",
"roomtype": "Entire Home",
"accommodates": "2",
"city": "Chandigarh",
"street_address": "",
"state": "Chandigarh 160017",
"zipcode": "",
"country": "India",
"latitude": "30.740212629732113",
"longitude": "76.78718557730713",
"address": "Bank Square, 17C, Sector 17, Chandigarh, Chandigarh 160017, India",
"bedrooms": "2",
"beds": "2",
"bathrooms": "1",
"from_date": "2015-07-16",
"to_date": "2015-08-19",
"available": "",
"amount_pernight": 100,
"currency": "INR",
"title": "AmazingSeaFacingPrivateRoom",
"summery": "Title should highlight the key features and will attract guests to choose your listing! Add an innovative title that best describes your home.rnrnExamples:rnrn Amazing Sea Facing Private Room!rn Fully Furnished Villa!rn Free Welcome Drink on Arrival!rn",
"mostcomman_facilities": "New Soap & Shampoo Sachet-:-Dry-cleaned Towel-:-Blanket-:-TV-:-Cable TV-:--:--:--:--:--:-",
"extra_facilities": "Extra Mattress-:-Extra Blanket-:-Washer-:-Alarm clock-:-Laundry Service-:-Gym-:--:--:--:--:-",
"features_facilities": "Smoking Allowed-:-Family & Children Friendly-:-Pets allowed-:-Wheelchair Available",
"safety_facilities": "Fire Extinguisher-:-Smoke Detector-:-Carbon Monoxide Detector-:-",
"num_bed": "0",
"bed_type": 2,
"currency_symbol": "",
"servicefee": "",
"cleaningfee": "",
"person": "all",
"landmark_location": "",
"landmark_distance": "",
"hostuniqueweb": "",
"hosttype": "web",
"extraperson": "Free",
"breakfast": "Free",
"Lunch": "Free",
"Dinner": "Free",
"Tea": "Free",
"Coffee": "Free",
"Airport": "Free"
},
"u0000yii\db\BaseActiveRecordu0000_oldAttributes": {
"hostid": 234,
"user_id": 77,
"hometype": "house",
"roomtype": "Entire Home",
"accommodates": "2",
"city": "Chandigarh",
"street_address": "",
"state": "Chandigarh 160017",
"zipcode": "",
"country": "India",
"latitude": "30.740212629732113",
"longitude": "76.78718557730713",
"address": "Bank Square, 17C, Sector 17, Chandigarh, Chandigarh 160017, India",
"bedrooms": "2",
"beds": "2",
"bathrooms": "1",
"from_date": "2015-07-16",
"to_date": "2015-08-19",
"available": "",
"amount_pernight": 100,
"currency": "INR",
"title": "AmazingSeaFacingPrivateRoom",
"summery": "Title should highlight the key features and will attract guests to choose your listing! Add an innovative title that best describes your home.rnrnExamples:rnrn Amazing Sea Facing Private Room!rn Fully Furnished Villa!rn Free Welcome Drink on Arrival!rn",
"mostcomman_facilities": "New Soap & Shampoo Sachet-:-Dry-cleaned Towel-:-Blanket-:-TV-:-Cable TV-:--:--:--:--:--:-",
"extra_facilities": "Extra Mattress-:-Extra Blanket-:-Washer-:-Alarm clock-:-Laundry Service-:-Gym-:--:--:--:--:-",
"features_facilities": "Smoking Allowed-:-Family & Children Friendly-:-Pets allowed-:-Wheelchair Available",
"safety_facilities": "Fire Extinguisher-:-Smoke Detector-:-Carbon Monoxide Detector-:-",
"num_bed": "0",
"bed_type": 2,
"currency_symbol": "",
"servicefee": "",
"cleaningfee": "",
"person": "all",
"landmark_location": "",
"landmark_distance": "",
"hostuniqueweb": "",
"hosttype": "web",
"extraperson": "Free",
"breakfast": "Free",
"Lunch": "Free",
"Dinner": "Free",
"Tea": "Free",
"Coffee": "Free",
"Airport": "Free"
},
"u0000yii\db\BaseActiveRecordu0000_related": [],
"u0000yii\base\Modelu0000_errors": null,
"u0000yii\base\Modelu0000_validators": null,
"u0000yii\base\Modelu0000_scenario": "default",
"u0000yii\base\Componentu0000_events": [],
"u0000yii\base\Componentu0000_behaviors": []
}
And here is my code for parsing this structure :
JSONObject obj = new JSONObject(jsonStr);
System.out.println("hello");
JSONObject ob=obj.getJSONObject("u0000yii\db\BaseActiveRecordu0000_attributes");
System.out.println("hello123");
home_type=ob.getString("home_type");
Log.v("home type is", home_type);
I am getting the following error in logcat. Here is the logcat details. plz help :
07-13 16:21:07.868: W/System.err(4678): org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
07-13 16:21:07.868: W/System.err(4678): at org.json.JSON.typeMismatch(JSON.java:111)
07-13 16:21:07.869: W/System.err(4678): at org.json.JSONObject.<init>(JSONObject.java:159)
07-13 16:21:07.869: W/System.err(4678): at org.json.JSONObject.<init>(JSONObject.java:172)
07-13 16:21:07.869: W/System.err(4678): at com.app.hostguestapp.Preview_form$Preview_form_data.doInBackground(Preview_form.java:91)
07-13 16:21:07.869: W/System.err(4678): at com.app.hostguestapp.Preview_form$Preview_form_data.doInBackground(Preview_form.java:1)
07-13 16:21:07.869: W/System.err(4678): at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-13 16:21:07.869: W/System.err(4678): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-13 16:21:07.870: W/System.err(4678): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-13 16:21:07.870: W/System.err(4678): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-13 16:21:07.870: W/System.err(4678): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
0 Пользователей и 1 Гость просматривают эту тему.
- 3 Ответов
- 3007 Просмотров
При нажатии на «Сохранить» после редактирования модуля пишет «Модуль успешно сохранен», но через примерно 10-20 секунд выдается ошибка на той же странице:
Ошибка
При обработке следующих JSON-данных произошла ошибка разбора:
Далее идет огромный текст ошибки в котором встречаются следующие строки:
<script>
(function() {
Joomla.JText.load({"JLIB_FORM_FIELD_INVALID":"u041du0435u043au043eu0440u0440u0435u043au0442u043du043e u0437u0430u043fu043eu043bu043du0435u043du043e u043fu043eu043bu0435: ","ERROR":"u041eu0448u0438u0431u043au0430","WARNING":"u041fu0440u0435u0434u0443u043fu0440u0435u0436u0434u0435u043du0438u0435","NOTICE":"u0412u043du0438u043cu0430u043du0438u0435","MESSAGE":"u0421u043eu043eu0431u0449u0435u043du0438u0435","JLIB_JS_AJAX_ERROR_CONNECTION_ABORT":"u041fu0440u043eu0438u0437u043eu0448u043bu043e u043fu0440u0435u0440u044bu0432u0430u043du0438u0435 u0441u043eu0435u0434u0438u043du0435u043du0438u044f u0432u043e u0432u0440u0435u043cu044f u0432u044bu0431u043eu0440u043au0438 u0434u0430u043du043du044bu0445 JSON.","JLIB_JS_AJAX_ERROR_NO_CONTENT":"u0421u043eu0434u0435u0440u0436u0438u043cu043eu0435 u043du0435 u0431u044bu043bu043e u0432u043eu0437u0432u0440u0430u0449u0435u043du043e.","JLIB_JS_AJAX_ERROR_OTHER":"u041fu0440u043eu0438u0437u043eu0448u043bu0430 u043eu0448u0438u0431u043au0430 u043fu0440u0438 u043fu043eu043bu0443u0447u0435u043du0438u0438 u0434u0430u043du043du044bu0445 JSON: u043au043eu0434 u0441u043eu0441u0442u043eu044fu043du0438u044f HTTP %s.","JLIB_JS_AJAX_ERROR_PARSE":"u041fu0440u0438 u043eu0431u0440u0430u0431u043eu0442u043au0435 u0441u043bu0435u0434u0443u044eu0449u0438u0445 JSON-u0434u0430u043du043du044bu0445 u043fu0440u043eu0438u0437u043eu0448u043bu0430 u043eu0448u0438u0431u043au0430 u0440u0430u0437u0431u043eu0440u0430: <br/> <code style="color:inherit;white-space:pre;padding:0;margin:0;border:0;background:inherit;">%s</code>","JLIB_JS_AJAX_ERROR_TIMEOUT":"u041fu0440u0435u0432u044bu0448u0435u043du043e u0432u0440u0435u043cu044f u043eu0436u0438u0434u0430u043du0438u044f u043eu0442u0432u0435u0442u0430 u043fu0440u0438 u0432u044bu0431u043eu0440u043au0435 u0434u0430u043du043du044bu0445 JSON."});
})();
</script>
А также админка немного притормаживает после открытия любого модуля и дает внести изменения только спустя несколько секунд.
В чем может быть причина? Прошу помочь! Все уже перепробовала, следуя советам форума.
Версия 3.6.5, Шаблон админки «isis — Default», но в «Менеджер расширений: Проверка базы данных» стоит почему-то вот что:
Версия схемы базы данных (из #__schemas): 3.6.3-2016-08-16.
Версия обновления (из #__extensions): 3.6.5.
При смене шаблона админки на «Hathor — Default» ошибка при сохранении модуля не появляется. Но этот шаблон мне не нравится. Как решить проблему в шаблоне «isis — Default»?
« Последнее редактирование: 18.12.2016, 03:53:30 от globus812 »
Записан
вот такое гуглится. делайте бакап базы и пробуйте
https://github.com/robwent/joomla-json-db-check
Спасибо! Это тоже делала. Но не помогло. Хотя сложно судить, поскольку это тоже может сыграло свою роль.
В итоге помогла установка новой версии плагина Sourcerer v4.4.7 до Sourcerer v6.3.7. После этого по предложению системы деинсталировала ненужный оставшийся от старой версии плагин.
Спасибо всем за помощь!
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:
The error message that I get when I click on ‘Save & Test’ button:
Software versions
Grafana | Zabbix | Grafana-Zabbix Plugin |
---|---|---|
7.1.1 | 5.0.1 | 4.0.0-alpha4 |
Hi! Could you show grafana-server logs?
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″
Ok, thanks for the details, I’ll try to reproduce this.
Could you also enable debug logging in grafana and post logs? It’s interesting, what’s an api method returns error.
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/
Hi,
Here is the post datas:
And the response:
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.
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.
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}
That’s strange. Could you check it against a different Zabbix server?
With zabbix.org it seems working:
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…
Same issue after upgrading in 5.0.3…
My zabbix server is on 4.2.6 and i have the same issue.
What’s an OS you’re running Grafana on, BTW?
Also, it might be related to SSL, so try to set Skip TLS Verify
option.
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
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).
That looks strange. Maybe it’s related to the go-http-client. I’ll check it out as well.
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.
@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.
@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.
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).
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 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.
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
@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.
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 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.
@Prefix yes, it’s definitely plugin issue.
@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…
@alexanderzobnin Here it is:
Here are 2 others examples that are working good, so we can see the differences:
-with postman:
-from another zabbix api client:
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
@mplm17 yes, this super helpful, thanks a lot!
Ok, I manage to replicate this bug. It’s related to request body. It seems, in some cases it’s not closed properly, so Content-Lenght
header is empty and Zabbix server can’t read request properly.
body = bytes.NewReader(reqBodyJSON) | |
rc, ok := body.(io.ReadCloser) | |
if !ok && body != nil { | |
rc = ioutil.NopCloser(body) | |
} |
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
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
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
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» возникает, когда декодирование кодирования не было успешным.
Сообщение
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
Тип ошибки
Что пошло не так?
JSON.parse()
обрабатывает (парсит) строку в формате JSON. Это строка должна соответствовать формату, иначе будет выведена ошибка, что был нарушен синтаксис.
Examples
JSON.parse()
не допускает запятые
Метод JSON.parse() не разрешает использование, так называемых, trailling запятых.
Обе строки выдадут ошибку типа SyntaxError:
JSON.parse('[1, 2, 3, 4,]');
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
Необходимо убрать последние запятые в строках и тогда ошибки не будет:
JSON.parse('[1, 2, 3, 4]');
JSON.parse('{"foo": 1}');
Названия свойств должны быть в двойных кавычках
Вы не можете использовать одинарные кавычки в именах свойств. Например, ‘foo’.
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
Вместо этого необходимо написать «foo»:
JSON.parse('{"foo": 1}');
Незначащие нули или плавающая точка без последующей цифры
Вы не можете использовать незначащие нули, например, 01. Плавающая точка должна всегда сопровождаться хотя бы одной цифрой после неё.
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data
JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data
Вместо этого напишите просто 1 без нуля и используйте хотя бы одну цифру после точки:
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
Смотрите также
15.02.2018, 11:49. Показов 3864. Ответов 6
Здравствуйте уважаемые форумчане. Столкнулся с проблемой, которую решить пока не могу.
На сайте большинство получение данных происходит через ajax.
Так вот, самое интересное, что у большинства людей работает все нормально, но есть некоторые у которых json.parse() выдает ошибку. Причем этот человек может с одного компьютера сидеть и все работает нормально, а с другого у него ошибку выдает.
И так. Пример…
Получаю список оценок за комментарии:
Javascript | ||
|
Далее php начинает обработку и формирование json
PHP | ||
|
И теперь пытаемся принять объект
Javascript | ||
|
Так вот… В большинстве случаев все и у всех работает нормально, но вот есть люди, у которых вылетает «Обработка JSON — не удалось распарсить»
Я пробовал к одному такому подключаться удаленно и смотрел что происходит в браузере.
А ничего необычного! Вот пример того что получаю я, у меня все работает (копировал из браузера из дебага на вкладке responce):
JSON | ||
|
И вот что у того человека:
JSON | ||
|
У него выдает ошибку json.
Но дама, на компьютере он говорит что все работает как надо. В браузере ctrl+f5 не помогает. Думал может файлы старые из кэша работают и мешают выполнению, но не помогает…
Всю голову сломал, помогите советом, что может быть?
Добавлено через 6 минут
Ах да… Нужно показать как json формируется
PHP | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0