从for循环创建json对象数组 [英] Create array of json objects from for loops

查看:778
本文介绍了从for循环创建json对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从html中提取值,然后将它们转换为json数组,到目前为止,我已经能够获得所需的内容,但只能作为单独的字符串:

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:

我做了两个for循环:

I did two for loops:

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}

(它们更长一些,但是您可以通过它获得一个主意...)

(they are longer but you can get an idea with this...)

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

How can I use python to create a json array out of these that would look like:

[{'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?

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

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.

推荐答案

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

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 :

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)

这篇关于从for循环创建json对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆