Python 从 for 循环创建 json 对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42865013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create array of json objects from for loops
提问by geekiechic
Im attempting to extract values from an html and then convert them into a json array, and so far I have been able to get what I want, but only as separate strings:
我试图从 html 中提取值,然后将它们转换为 json 数组,到目前为止我已经能够得到我想要的,但只能作为单独的字符串:
I did two for loops:
我做了两个 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
Which produce these two outputs:
产生这两个输出:
{'Title': 'Uncanny Valley'}
{'Title': 'Subject 13'}
{'Title': '2Dark'}
{'Title': 'Lethal VR'}
{'Title': 'Earthlock: Festival of Magic'}
{'Title': 'Knee Deep'}
{'Title': 'VR Ping Pong'}
and
和
{'Score': 73}
{'Score': 73}
{'Score': 72}
{'Score': 72}
{'Score': 72}
{'Score': 71}
{'Score': 71}
(they are longer but you can get an idea with this...)
(它们更长,但您可以对此有所了解......)
How can I use python to create a json array out of these that would look like:
我如何使用 python 从这些中创建一个 json 数组,如下所示:
[{'Title': 'Uncanny Valley', 'Score': 73}, {....}]
I am gonna use the resulting array to do other things afterwards....
之后我将使用生成的数组来做其他事情......
Do I need to store the items from the loop into lists and then merge them? Could you please illustrate an example given my scenario?
我是否需要将循环中的项目存储到列表中然后合并它们?您能否举例说明我的情况?
Help is much appreciated, this is a really cool learning experience for me as I have only used bash until now. Python looks way sexier.
非常感谢帮助,这对我来说是一次非常酷的学习体验,因为我到目前为止只使用过 bash。Python 看起来更性感。
回答by ZdaR
You need to maintain two lists for scores and titles and append all the data to those lists, instead of printing, and then zip
those lists along with list comprehension to get the desired output as :
您需要维护两个分数和标题列表,并将所有数据附加到这些列表中,而不是打印,然后将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)