How can I validate & beautify JSON through a jquery/javascript plugin
Asked Answered
T

2

5

I have a requirement where in I get JSON data from backend and I have to show that in textarea.currently, the data comes but its not formatted and validated.Now

1)How can I beautify JSON in the textarea ? 2)How can I validate it before saving ?

I have searched for all javascript/jquery plugins but I am not getting what I want.I want something like jslint

Thanks in advance

Theft answered 4/4, 2016 at 13:43 Comment(0)
S
4

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

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

Usage:

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

If you also need to validate the object using some custom logic (e.g. "I need your object to have attributes X and Y"), take a look at JsonSchema.

Starobin answered 4/4, 2016 at 13:48 Comment(0)
J
14

Use JSON.stringify(object, 0, 4) with space parameter for a 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>');
Jujube answered 4/4, 2016 at 13:45 Comment(1)
Nice! Never heard of itStarobin
S
4

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

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

Usage:

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

If you also need to validate the object using some custom logic (e.g. "I need your object to have attributes X and Y"), take a look at JsonSchema.

Starobin answered 4/4, 2016 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.