如何用Python解析/提取嵌套的JSON数据?

时间:2018-04-06 17:09:31

标签: python arrays json parsing nested-lists

我目前正在尝试从包含嵌套数据的JSON Feed中提取产品数据。

嵌套结构如下所示:http://live.icecat.biz/api/?shopname=openIcecat-live&lang=en&content=featuregroups&icecat_id=1334921

我基本上想要提取数据库中产品的基本数据表信息。每个产品在“顶层”具有不同的特征类别,并且在嵌套结构中具有不同的特征。

到目前为止,我的代码看起来像这样:

import requests
url2 = 'http://live.icecat.biz/api/?shopname=openIcecat-live&lang=de&content=featuregroups&icecat_id=1334921'

content = requests.get(url).content

j = json.loads(content)    

for each in j['data']['FeaturesGroups']:
    print each ['FeatureGroup']['Name']['Value']

它工作正常并打印每个要素类别的标题。但我无法解析各个功能。我怎么能这样做?

我的尝试是使用第二个循环迭代j ['data'] ['FeaturesGroups'] ['Features'](见下文),但没有成功:/

for each in j['data']['FeaturesGroups']:
    for each in ['Features']:
        print ['Feature']['ID']

非常感谢!

2 个答案:

答案 0 :(得分:2)

import requests
import json
url2 = 'http://live.icecat.biz/api/?shopname=openIcecat-live&lang=de&content=featuregroups&icecat_id=1334921'

content = requests.get(url2).content

j = json.loads(content)

for each in j['data']['FeaturesGroups']:
    print each['FeatureGroup']['Name']['Value']
    for i in each["Features"]:
        print i["ID"]

答案 1 :(得分:1)

import requests
import json
url = 'http://live.icecat.biz/api/?shopname=openIcecat-live&lang=de&content=featuregroups&icecat_id=1334921'

content = requests.get(url).content

j = json.loads(content)    

def find_all(item, level):
    if isinstance(item, dict):
        for k in item:
            print k
            find_all(item[k],level+1)
    else:
        print ' '*level ,item

for each in j['data']['FeaturesGroups']:
    find_all(each['FeatureGroup'], 0)


ID
  3
Name
Language
   DE
ID
   437975
Value
   Speicher
ID
  28
Name
Language
   DE
ID
   437998
Value
   Betriebsbedingungen
ID
  146
Name
Language
   DE
ID
   624349
Value
   Weitere Spezifikationen