Convert array of JSON object strings to array of JS objects

后端 未结 3 679
悲&欢浪女
悲&欢浪女 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 05:56

    If you have a JS array of JSON objects:

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

    and you want an array of objects:

    // JavaScript array of JavaScript objects
    var objs = s.map(JSON.parse);
    
    // ...or for older browsers
    var objs=[];
    for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);
    
    // ...or for maximum speed:
    var objs = JSON.parse('['+s.join(',')+']');
    

    See the speed tests for browser comparisons.


    If you have a single JSON string representing an array of objects:

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

    and you want an array of objects:

    // JavaScript array of JavaScript objects
    var objs = JSON.parse(s);
    

    If you have an array of objects:

    // A JavaScript array of JavaScript objects
    var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];
    

    …and you want JSON representation for it, then:

    // JSON string representing an array of objects
    var json = JSON.stringify(s);
    

    …or if you want a JavaScript array of JSON strings, then:

    // JavaScript array of strings (that are each a JSON object)
    var jsons = s.map(JSON.stringify);
    
    // ...or for older browsers
    var jsons=[];
    for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);
    
    0 讨论(0)
  • If you really have:

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

    then simply:

    var objs = $.map(s, $.parseJSON);
    

    Here's a demo.

    0 讨论(0)
  • 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("<json string here>")

    0 讨论(0)
提交回复
热议问题