Convert array of JSON object strings to array of JS objects

后端 未结 3 689
悲&欢浪女
悲&欢浪女 2020-12-08 05:23

I would like to convert an array of JSON String to array of JSON object without looping through each item and parse it using JSON.parse.

Example:

var         


        
3条回答
  •  轮回少年
    2020-12-08 06:04

    var json = jQuery.parseJSON(s); //If you have jQuery.
    

    Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

    var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
    

    Change the above code to

    var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
    

    Eg:

    $(document).ready(function() {
        var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
    
        s = jQuery.parseJSON(s);
    
        alert( s[0]["Select"] );
    });
    

    And then use the parse function. It'll surely work.

    EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

    Jquery

    The json api

    Edit (30 April 2020):

    Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("")

提交回复
热议问题