Python - 从for循环创建json对象数组

gee*_*hic 12 python maps json loops list

我试图从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
Run Code Online (Sandbox Code Playgroud)

产生这两个输出:

{'Title': 'Uncanny Valley'}
{'Title': 'Subject 13'}
{'Title': '2Dark'}
{'Title': 'Lethal VR'}
{'Title': 'Earthlock: Festival of Magic'}
{'Title': 'Knee Deep'}
{'Title': 'VR Ping Pong'}
Run Code Online (Sandbox Code Playgroud)

{'Score': 73}
{'Score': 73}
{'Score': 72}
{'Score': 72}
{'Score': 72}
{'Score': 71}
{'Score': 71}
Run Code Online (Sandbox Code Playgroud)

(它们更长,但你可以对此有所了解...)

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

[{'Title': 'Uncanny Valley', 'Score': 73}, {....}]
Run Code Online (Sandbox Code Playgroud)

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

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

非常感谢帮助,这对我来说是一次非常酷的学习体验,因为我直到现在才使用bash.Python看起来更性感.

Zda*_*daR 21

您需要为分数和标题维护两个列表,并将所有数据附加到这些列表,而不是打印,然后将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)
Run Code Online (Sandbox Code Playgroud)

  • @geekiechic 这个答案的核心很重要:你不手动构建`json` 字符串,构建相应的python 数据结构,并使用`json` 模块*序列化*。 (2认同)