对json数据的迭代由许多None类型的对象组成

2024-04-18 19:13:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试迭代json数据。这是我的数据结构

import requests
import re
url = "https://web.archive.org/__wb/calendarcaptures?url=http%3A%2F%2Fwww.unibocconi.it&selected_year=2014"
# You can see the data structure by copy-pasting the link
data = requests.get(url).json()
    for x in data:
       for y in x:
           for z in y:
               for xx in z:
                    start1 = "'ts': "
                    start2 = "'st': "
                    h = str(xx)
                    a = re.search('%s(.*)' % (start1) , h).group(1)
                    date = a[:16].replace("[", "").replace("]", "")
                    date = re.sub("[^0-9]", "", date)
                    b = re.search('%s(.*)' % (start2) , h).group(1)
                    status = b[:5].replace("[", "").replace("]", "")

我知道,我不能迭代无类型的对象。但我有几个小时没能解决这个问题。有什么想法吗? 注意:我使用请求直接从web获取json数据


Tags: the数据inimportrewebjsonurl
2条回答

如果您真正想要的只是count/statuscode/timestamp值,则不需要逐字解析json列表。Python将根据需要将json作为list/dict拉入。因此,要通过任何“None”值,请使用“if z:”条件语句。你知道吗

一旦到达z存在的位置,z.get('cnt','')将在该字段存在时拉取该字段,如果该字段不存在,则不返回任何内容。然后可以使用pop进入状态/日期列表。我写那部分的方式不太优雅,但它能完成任务。(这假设状态/时间戳列表的长度始终为1。如果不是这样的话,您可以很容易地在其中插入一些其他逻辑/索引,以提取您感兴趣的值。)

for x in data:
    for y in x:
        for z in y:
            if z:
                count = z.get('cnt', '')
                st = z.get('st', '')
                if st:
                    status = st.pop()
                ts = z.get('ts', '')
                if ts:
                    date = ts.pop()

print(count, status, date)

2 200 20140308061038

更新:数据类型为列表。你知道吗

json_acceptable_string = data.replace("'", "\"").replace('None', 'null')
d = json.loads(json_acceptable_string)

相关问题 更多 >