How can I test and decorate JSON through jquery / javascript plugin

I have a requirement when I get JSON data from the backend, and I have to show that in textarea.currently the data is coming in, but not formatted or verified. Now

1) How can I decorate JSON in a text box? 2) How can I check it before saving?

I searched all javascript / jquery plugins, but I don't get what I want. I need something like jslint

Thank you in advance

+5
source share
2 answers

You can use the following to verify that the string is a valid representation of the JSON object:

function parseJson(str) { try { return JSON.parse(str); } catch (err) { return false; } } 

Using:

 var parsed = parseJson(someInput); if (parsed === false) { // Invalid json } 

If you also need to validate the object using some custom logic (for example, โ€œI need your object to have X and Y attributesโ€), check out JsonSchema .

+4
source

Use JSON.stringify(object, 0, 4) with a space parameter for the formatted JSON string.

 var object = [{ "stop_id": 70021, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70022, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70151, "stop_name": "CALTRAIN - ATHERTON STATION", "stop_lat": 37.464458, "stop_lon": -122.198152, "zone_id": 3331 }]; document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>'); 
+15
source

Source: https://habr.com/ru/post/1246413/


All Articles