【问题标题】:Create array of json objects from for loops从 for 循环创建 json 对象数组
【发布时间】:2017-08-09 10:52:54
【问题描述】:

我试图从 html 中提取值,然后将它们转换为 json 数组,到目前为止,我已经能够得到我想要的,但只能作为单独的字符串:

我做了两个 for 循环:

for line in games_html.findAll('div', class_="product_score"):
  score= ("{'Score': %s}" % line.getText(strip=True))
  print score

for line in games_html.findAll('a'):
  title= ("{'Title': '%s'}" % line.getText(strip=True))
  print title

产生这两个输出:

{'Title': 'Uncanny Valley'}
{'Title': 'Subject 13'}
{'Title': '2Dark'}
{'Title': 'Lethal VR'}
{'Title': 'Earthlock: Festival of Magic'}
{'Title': 'Knee Deep'}
{'Title': 'VR Ping Pong'}

{'Score': 73}
{'Score': 73}
{'Score': 72}
{'Score': 72}
{'Score': 72}
{'Score': 71}
{'Score': 71}

(它们更长,但你可以通过这个得到一个想法......)

如何使用 python 从这些中创建一个 json 数组,如下所示:

[{'Title': 'Uncanny Valley', 'Score': 73}, {....}]

之后我将使用生成的数组来做其他事情......

我是否需要将循环中的项目存储到列表中然后合并它们?您能否根据我的情况举例说明?

非常感谢您的帮助,这对我来说是一次非常酷的学习体验,因为到目前为止我只使用过 bash。 Python 看起来更性感。

【问题讨论】:

  • 提示:使用新的.format 字符串格式,而不是非常旧且更有限的% 字符串格式。
  • 所以我以一种不推荐的方式学习这个:(,感谢您指出这一点

标签: python json list loops maps


【解决方案1】:

您需要为分数和标题维护两个列表,并将所有数据附加到这些列表中,而不是打印,然后 zip 这些列表以及列表理解以获得所需的输出:

import json
scores, titles = [], []
for line in games_html.findAll('div', class_="product_score"):
    scores.append(line.getText(strip=True))

for line in games_html.findAll('a'):
    titles.append(line.getText(strip=True))

score_titles = [{"Title": t, "Score": s} for t, s in zip(titles, scores)]
print score_titles
# Printing in JSON format
print json.dumps(score_titles)

【讨论】:

  • 嘿,谢谢,实际上我只是打印以可视化我在做什么,哈哈,这些对我来说是非常新的概念,这是一次很好的反复试验,我现在将用你的建议进行测试解决方案,再次感谢!
  • @geekiechic 这个答案的核心很重要:你不要手动构建json 字符串,构建相应的python数据结构,然后使用@987654324 序列化它 @模块。
  • @juanpa.arrivillaga 所以想法是先创建合并列表,而不尝试构建 json 字符串,然后在该列表上使用 json.dumps()?此外,这很奇怪,但无论我将变量放在 score_titles 中的顺序如何 = 当我打印时,“分数”总是排在第一位(?)
  • @geekiechic 字典(就此而言,JSON 对象)本质上是无序的。
  • @geekiechic 试试print(json.dumps(my_object, indent=2)).
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2018-08-12
  • 1970-01-01
  • 2012-09-11
  • 2021-09-11
  • 1970-01-01
相关资源
最近更新 更多