简体   繁体   中英

`jQuery.parseJSON` function in only javascript (without jQuery)

I was looking for the method to do jQuery.parseJSON in JavaScript that parses a json to return a JavaScript object. I can't use jQuery since the whole plugin that I have built is standalone JS and no jQuery has been used till now. Is there something of this sort that's already provided in JavaScript?

Use the native JSON object (this is the only time it is correct to say "JSON object", it is literally an object named JSON ) to manipulate JSON strings.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON

Use JSON.parse(yourJSONString); to serialize and JSON.stringify(yourJSONObject); to deserialize.

If you look at the jQuery core source on line 492, jQuery.parseJSON is just an alias to JSON.parse .

You can either use the native JSON object , which is supported in most browsers, but you will run into an issue when you try to use it in the dinosaur browsers such as IE7 and lower. There is the option to include a standalone plugin that mimics native functionality here (JSON.js).

Short answer:

Use the browser native method JSON.parse()

window.JSON.parse(jsonString);

Long answer:

To get it working in old browsers, you can take the source code of jQuery.parseJSON and remove any dependencies on jQuery itself. Here is a working standalone version:

function standaloneParseJson ( data ) {
    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    if ( data === null ) {
        return data;
    }

    var rvalidchars = /^[\],:{}\s]*$/;
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g;
    var rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g;

    if ( typeof data === "string" ) {

        // Make sure leading/trailing whitespace is removed (IE can't handle it)
        data = data.replace(/^\s+|\s+$/g, '');

        if ( data ) {
            // Make sure the incoming data is actual JSON
            // Logic borrowed from http://json.org/json2.js
            if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                .replace( rvalidtokens, "]" )
                .replace( rvalidbraces, "")) ) {

                return ( new Function( "return " + data ) )();
            }
        }
    }

    // Error code here
    //jQuery.error( "Invalid JSON: " + data );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM