转换这个:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}
对此:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"}
即... {id: 数量}
我找到了一个几乎可以满足我需要的答案:Searching for an Object inside the JSON .但是这个答案对我没有帮助,因为它只是在第一级(一个 json 对象)。我的问题在第二级(json 对象中的 json 对象)。提前致谢!
最佳答案
如果您不将 JSON 对象视为 JSON 对象,这会有所帮助。一旦你通过 JSON.parse 运行一个 JSON 字符串,它就是一个原生的 JavaScript 对象。
在 JavaScript 中,有两种访问对象的方法。
点符号
点符号是这样的
myObject.name
看到那个点了吗?您可以使用它来访问任何对象 property(实际上它可能是 javascript 中的另一个对象,只要它具有有效的点符号名称)。您不能使用像 -
这样的字符, .
, 和空格字符。
Bracket Notation(可能是另一个名字)
myObject["variableName"]
类似于点符号,但允许一些其他字符,如 -
和空格字符..做完全一样的事情。
使用这些符号很有用,因为我们可以访问嵌套属性。
myObj.foo.bar.baz()
现在让我们来看看您的 JSON 对象...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},<br/>
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
您可能想复习一下 JSON format你自己,但在你的例子中,这里有一些线索......
{
表示一个对象的开始。 (请记住,您的整个 JSON 字符串本身就是一个对象。)
}
表示一个对象的结束。
"variable"
(带引号!在 JSON 中很重要,但在访问/声明 javascript 对象时不是)为您的对象分配一个属性。
:
是 JSON 和 JavaScript 对象中的赋值运算符。
:
右边的任何内容是您分配给左侧属性的值。
,
意味着您正在对象中启动一个新属性。
您可能知道 []
与 ,
里面的逗号表示一个数组。
当我们通过 JSON.parse(string)
运行您的字符串时,我们会得到一个看起来像这样的对象......
var myResponse = JSON.parse(response);
您现在可以将其用作 native JavaScript 对象。您正在寻找的是“项目”中的嵌套属性。
var items = myResponse.items; //alternatively you could just use myResponse.items
自 items
是一个对象数组,我们需要遍历它以便将现有对象转换为新对象。
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.
Result 现在是一个看起来像这样的对象:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}
您可以使用括号表示法访问属性。
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
关于javascript - 如何提取 json 对象中的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368171/