JQuery Parsing JSON array

后端 未结 5 1195
情话喂你
情话喂你 2020-12-02 11:46

I have a JSON output like the following:

[\"City1\",\"City2\",\"City3\"]

I want to get each of the city names, how can i do th

相关标签:
5条回答
  • 2020-12-02 11:55

    getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

    You can get all the values in an array using a for loop:

    $.getJSON("url_with_json_here", function(data){
        for (var i = 0, len = data.length; i < len; i++) {
            console.log(data[i]);
        }
    });
    

    Check your console to see the output (Chrome, Firefox/Firebug, IE).

    jQuery also provides $.each() for iterations, so you could also do this:

    $.getJSON("url_with_json_here", function(data){
        $.each(data, function (index, value) {
            console.log(value);
        });
    });
    
    0 讨论(0)
  • 2020-12-02 12:04

    Use the parseJSON method:

    var json = '["City1","City2","City3"]';
    var arr = $.parseJSON(json);
    

    Then you have an array with the city names.

    0 讨论(0)
  • 2020-12-02 12:13
    var dataArray = [];
    var obj = jQuery.parseJSON(yourInput);
    
    $.each(obj, function (index, value) {
        dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
    });
    

    this helps me a lot :-)

    0 讨论(0)
  • 2020-12-02 12:14
    var dataArray = [];
    var obj = jQuery.parseJSON(response);
      for( key in obj ) 
      dataArray.push([key.toString(), obj [key]]);
    };
    
    0 讨论(0)
  • 2020-12-02 12:15

    with parse.JSON

    var obj = jQuery.parseJSON( '{ "name": "John" }' );
    alert( obj.name === "John" );
    
    0 讨论(0)
提交回复
热议问题