转换这个:
{"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"}
Run Code Online (Sandbox Code Playgroud)
对此:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"} 那是... {id:quantity}
我找到了一个几乎可以满足我需要的答案:在JSON中搜索一个Object.但是这个答案对我没有帮助,因为它只在第一级(一个json对象).我的问题是在第二级(json对象中的json对象).提前致谢!
Sta*_*art 31
如果您不将JSON对象视为JSON对象,则会有所帮助.通过JSON.parse运行JSON字符串后,它就是一个本机JavaScript对象.
在JavaScript中,有两种访问对象的方法.
点符号就是这样的
myObject.name
看点?您可以使用它来访问任何对象属性(实际上可能是javascript中的另一个对象,只要它具有有效的点表示法名称).你不能使用像字符-,.和空格字符.
myObject["variableName"]
像点符号,但允许一些其他字符,如-和空格字符..完全相同的事情.
使用这些表示法很有用,因为我们可以访问嵌套属性.
myObj.foo.bar.baz()
现在让我们来看看你的JSON对象......
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
您可能想要自己刷新JSON格式,但在您的示例中,这里有一些线索......
{表示对象的开始.(请记住,整个JSON字符串本身就是一个对象.)
} 表示对象的结尾.
"variable" (带引号!在JSON中很重要,但在访问/声明javascript对象时却没有)为您的对象分配属性.
:是JSON和JavaScript对象中的赋值运算符.右侧的任何内容:都是您在左侧分配给该属性的值.
, 表示您在对象中启动新属性.
您可能知道内部[]使用,逗号表示数组.
当我们运行你的字符串时JSON.parse(string),我们将得到一个看起来像这样的对象......
var myResponse = JSON.parse(response);
您现在可以将其用作本机JavaScript对象.你要找的是"items"中的嵌套属性.
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.
Run Code Online (Sandbox Code Playgroud)
结果现在是一个看起来像这样的对象:
{
"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!
}
Run Code Online (Sandbox Code Playgroud)
您可以使用括号表示法访问属性.
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
| 归档时间: |
|
| 查看次数: |
44173 次 |
| 最近记录: |