簡體   English   中英

使用JavaScript從JSON獲取數組

[英]Get array from json using javascript

服務器返回我這樣的對象,但我只需要數組ITEMS。 我怎么才能得到它? 我試過array['items']但結果不undefiend

{
   "items": [
    {
      ..
    },
    {
      ..
    },
    {
      ..
    }
  ],.. 
  ,..
}
// JSON string returned from the server
var text = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}';

// Convert the string returned from the server into a JavaScript object.
var object = JSON.parse(text);

// Accessing a specific property value of an item
console.log(object.items[0].name); //itemX

// Extract 'items' in to a separate array
var itemsArray = object.items;
console.log(itemsArray); //[itemObject, itemObject, itemObject]

如果將其作為字符串獲取:

var json = JSON.parse(my_json_string)

然后,

var keys = Object.keys(json);
var values = [];
for(var i = 0; i < keys.length; i++){
    values.push(json[keys[i]]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM