在没有显式访问键的情况下在Python中进行JSON解析

时间:2016-11-26 17:46:08

标签: python json

JSON数据:

angle = 360 * percentage / 100;

预期产出:

angle = 360f / 100f * percentage;

类似于id = 3的东西。

更新

到目前为止我做了什么:

[
 {
  "id": 2,
  "name": "An ice sculpture",
  "price": 12.50,
 },

 {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
 }
]

错误:

id - 2
name - An ice sculpture
price - 12.50

我发现大部分数据都是使用content = urllib.request.urlopen(url).read().decode('utf-8') content = content.replace("//" , "").strip() #there is a // at the beginning obj = json.loads(content) for obj in content: for key, value in obj.items(): print (obj.key, obj.value) 输出File "test.py", line 22, in get for key, value in obj.items(): AttributeError: 'str' object has no attribute 'items' 等属性键直接访问的。有没有办法在没有明确访问密钥的情况下获得预期的输出?

2 个答案:

答案 0 :(得分:3)

您有一个词典列表。只要您遍历外部列表,您的代码就可以工作:

for obj in my_json_data:
    for key, value in obj.items():
         print (obj.key, obj.value)

答案 1 :(得分:0)

你应该试试这个

data = [
 {
  "id": 2,
  "name": "An ice sculpture",
  "price": 12.50,
 },

 {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
 }
]

for json_data in data:
    for k, v in json_data.items():
        print('{} - {}'.format(k,v))