简体   繁体   中英

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']

data[u'X'] results in:

{
  "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.

What if the JSON structure will be changed in the future? 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:

{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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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