简体   繁体   English

使用Python获取特定JSON值的更可靠方法

[英]More reliable method to get specific JSON value using Python

Based on this Q&A a certain JSON value can be found using print data[u'X'][50][u'Z'] 根据此问答,可以使用print data[u'X'][50][u'Z']找到某个JSON值

data[u'X'] results in: data[u'X']导致:

{
  "X" : [ {
    "A" : "B",
    ...
  }, {
    ...
  }, {
    "C" : "D",
  } ]
}

Applying the integer method means that every part that is separated by a comma, eg "element" : [ { "name" : "value", ... }, needs to be counted until the required piece has been found, in this case number 50. 应用整数方法意味着需要用逗号分隔每个部分,例如"element" : [ { "name" : "value", ... },直到找到所需的部分为止。 50。

What if the JSON structure will be changed in the future? 如果将来会更改JSON结构怎么办? Does this mean that the integer should be updated every time? 这是否意味着该整数应该每次都更新?

In my opinion this method is fragile. 我认为这种方法很脆弱。 How to make it more reliable? 如何使其更可靠?

Attempts 尝试次数

print data[u'X'][0] results in: print data[u'X'][0]导致:

{u'A': u'B', u'C': u'D'}

while

print data[u'X'][u'A']

results in: 结果是:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print data[u'beans'][u'modelerType']
TypeError: list indices must be integers, not unicode

There are 2 types of collections in JSON, arrays and objects (see the API for more info) JSON中有2种类型的集合,数组和对象(有关更多信息,请参阅API)

For example, a list of items: 例如,项目列表:

x = ['a', 'b', 'c', 'd']
x[2] // Returns 'c'

And an object: 还有一个对象:

x = {"a": 10, "b": 20, "c": 30}
x['b'] // Returns 20

So assuming you use an object to store the data than you won't need an index number at all, just the name of the property. 因此,假设您使用一个对象来存储数据,则根本不需要索引号,而只需要属性的名称。 If you use the list, than you will have to store the list index. 如果使用列表,则必须存储列表索引。

It is possible to store an array in an object and vice versa. 可以将数组存储在对象中,反之亦然。 For example: 例如:

x = [1, 2, 3, {"a": 10, "b": 20, "c": [30, 40, 50]}]
x[0] // Returns 1
x[3] // Returns {"a": 10, "b": 20, "c": [30, 40, 50]}
x[3]['a'] // Returns 10
x[3]['c'][2] // Returns 50

This is probably closer to what you're looking for: 这可能更接近您要查找的内容:

models = ['JvmMetrics', 'MyMetrics']
filtered = filter(ldata['beans'], lambda x: x['modelerType'] in models)

It's unlikely that there's a better way unless you want to build another dict from the JMX response. 除非您想根据JMX响应构建另一个指令,否则不可能有更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM