【问题标题】:How can I make json data from requests into excel file?如何将请求中的 json 数据转换为 excel 文件?
【发布时间】:2019-11-16 10:53:43
【问题描述】:

这是我第一次处理 json 数据。所以我对json的结构不是很熟悉。

我通过“we the people”电子请愿网站获得了一些数据,代码如下:

url = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"
jdata_2 = requests.get(url).json()

然而,我意识到这与普通的 json 结构有所不同,因为我在尝试使用 pandas 将其转换为 excel 文件时遇到了一些错误

df = pandas.read_json(jdata_2)

显然,我必须错过在使用 pandas.read_json() 代码之前必须完成的一些事情。 我已经搜索了答案,但大多数问题是“如何将 json 数据转换为 excel 数据”,这需要 json 数据。就我而言,我从 url 中抓取了它,所以我想我可以将这些字符串转换为 json 数据,然后尝试将其转换为 excel 数据。所以我也尝试使用 json.dump(),但效果不佳。

我知道这一定是个幼稚的问题。但我不确定我可以从这个幼稚的问题开始。如果有人能指导我如何处理它,我将不胜感激。或者链接我一些我也可以学习的参考资料。

提前感谢您的帮助。

这是带有请求的 json 数据,我用 indent=4 打印它。

输入:

url = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(jdata_2)

输出:

{   'metadata': {   'requestInfo': {   'apiVersion': 1,
                                   'query': {   'body': None,
                                                'createdAfter': None,
                                                'createdAt': None,
                                                'createdBefore': '1573862400',
                                                'isPublic': 1,
                                                'isSignable': None,
                                                'limit': '3',
                                                'mock': 0,
                                                'offset': '0',
                                                'petitionsDefaultLimit': '1000',
                                                'publicThreshold': 149,
                                                'responseId': None,
                                                'signatureCount': None,
                                                'signatureCountCeiling': None,
                                                'signatureCountFloor': 0,
                                                'signatureThreshold': None,
                                                'signatureThresholdCeiling': None,
                                                'signatureThresholdFloor': None,
                                                'sortBy': 'DATE_REACHED_PUBLIC',
                                                'sortOrder': 'ASC',
                                                'status': None,
                                                'title': None,
                                                'url': None,
                                                'websiteUrl': 'https://petitions.whitehouse.gov'},
                                   'resource': 'petitions'},
                'responseInfo': {   'developerMessage': 'OK',
                                    'errorCode': '',
                                    'moreInfo': '',
                                    'status': 200,
                                    'userMessage': ''},
                'resultset': {'count': 1852, 'limit': 3, 'offset': 0}},
'results': [   {   'body': 'Please save kurdish people in syria \r\n'
                           'pleaee save north syria',
                   'created': 1570630389,
                   'deadline': 1573225989,
                   'id': '2798897',
                   'isPublic': True,
                   'isSignable': False,
                   'issues': [   {   'id': 326,
                                     'name': 'Homeland Security & '
                                             'Defense'}],
                   'petition_type': [   {   'id': 291,
                                            'name': 'Call on Congress to '
                                                    'act on an issue'}],
                   'reachedPublic': 0,
                   'response': [],
                   'signatureCount': 149,
                   'signatureThreshold': 100000,
                   'signaturesNeeded': 99851,
                   'status': 'closed',
                   'title': 'Please save rojava north syria\r\n'
                            'please save kurdish people\r\n'
                            'please stop erdogan\r\n'
                            'plaease please',
                   'type': 'petition',
                   'url': 'https://petitions.whitehouse.gov/petition/please-save-rojava-north-syria-please-save-kurdish-people-please-stop-erdogan-plaease-please'},
               {   'body': 'Kane Friess was a 2 year old boy who was '
                           "murdered by his mom's boyfriend, Gyasi "
                           'Campbell. Even with expert statements from '
                           'forensic anthropologists, stating his injuries '
                           'wete the result of homicide. Mr. Campbell was '
                           'found guilty of involuntary manslaughter. This '
                           "is an outrage to Kane's Family and our "
                           'community.',
                   'created': 1566053365,
                   'deadline': 1568645365,
                   'id': '2782248',
                   'isPublic': True,
                   'isSignable': False,
                   'issues': [   {   'id': 321,
                                     'name': 'Criminal Justice Reform'}],
                   'petition_type': [   {   'id': 281,
                                            'name': 'Change an existing '
                                                    'Administration '
                                                    'policy'}],
                   'reachedPublic': 0,
                   'response': [],
                   'signatureCount': 149,
                   'signatureThreshold': 100000,
                   'signaturesNeeded': 99851,
                   'status': 'closed',
                   'title': "Kane's Law. Upon which the murder of a child, "
                            'regardless of circumstances, be seen as 1st '
                            'degree murder.  A Federal Law.',
                   'type': 'petition',
                   'url': 'https://petitions.whitehouse.gov/petition/kanes-law-upon-which-murder-child-regardless-circumstances-be-seen-1st-degree-murder-federal-law'},
               {   'body': "Schumer and Pelosi's hatred and refusing to "
                           'work with President Donald J. Trump is holding '
                           'America hostage. We the people know securing '
                           'our southern border is a priority which will '
                           'not happen with these two in office. Lets '
                           'build the wall NOW!',
                   'created': 1547050064,
                   'deadline': 1549642064,
                   'id': '2722358',
                   'isPublic': True,
                   'isSignable': False,
                   'issues': [   {'id': 306, 'name': 'Budget & Taxes'},
                                 {   'id': 326,
                                     'name': 'Homeland Security & '
                                             'Defense'},
                                 {'id': 29, 'name': 'Immigration'}],
                   'petition_type': [   {   'id': 291,
                                            'name': 'Call on Congress to '
                                                    'act on an issue'}],
                   'reachedPublic': 0,
                   'response': [],
                   'signatureCount': 149,
                   'signatureThreshold': 100000,
                   'signaturesNeeded': 99851,
                   'status': 'closed',
                   'title': 'Remove Chuck Schumer and Nancy Pelosi from '
                            'office',
                   'type': 'petition',
                   'url': 'https://petitions.whitehouse.gov/petition/remove-chuck-schumer-and-nancy-pelosi-office'}]}

这是我收到的错误消息 输入:

df = pandas.read_json(jdata_2)

输出:

ValueError: Invalid file path or buffer object type: <class 'dict'>

【问题讨论】:

  • 您没有显示导致错误的 JSON,也没有指定错误是什么。如果您希望其他人帮助您处理特定案例,两者都是基本的。您说您不熟悉 JSON(这没关系),并表示希望了解更多信息(这很好),但随后您要求提供参考链接……您是否尝试过仅使用 Google 搜索?这不像是一些深奥的主题,只有少数人可以确定必要的资源。它是 JSON...
  • @obe 对不起那个obe。实际上,我提到了参考资料,因为我认为对于可以回答的人来说可能会容易得多。我现在也在谷歌上搜索 json。我无意成为懒惰的工人。但是由于关于 json 的信息太多了,所以我从头开始处理。所以需要一段时间。再次抱歉,如果这可能令人反感。我编辑了json和错误。我忘了附上它。再次抱歉。
  • 不用担心......不幸的是,我对 Python 不太熟悉,但我不确定我是否理解应该如何将这样的 JSON 保存到 Excel 文件中。它具有复杂的层次结构,而不仅仅是扁平的键值结构。无论如何,我可能会执行以下步骤:(1)将失败的 JSON “硬编码”为字符串,然后尝试使用它。 (2) 失败后 - 简化 JSON(基本上从中删除一些键),然后重试。如果它仍然失败 - 剥离更多,直到它成功。一旦成功 - 开始重新构建原始 JSON。最终你会找出问题所在..
  • @obe 谢谢obe。 abhikumar22 告诉我我在将 json 文件转换为字典时出错了。我应该更多地研究 pd 和 json 参考。再次感谢您。

标签: python json python-3.x


【解决方案1】:

你也可以试试下面的代码,效果很好

URL = "https://api.whitehouse.gov/v1/petitions.json?limit=3&offset=0&createdBefore=1573862400"

// fetching the json response from the URL
req = requests.get(URL)
text_data= req.text
json_dict= json.loads(text_data)

//converting json dictionary to python dataframe for results object
df = pd.DataFrame.from_dict(json_dict["results"])

最后,将数据框保存为 excel 格式,即 xlsx

df.to_excel("output.xlsx") 

【讨论】:

  • 天哪。所以我的尝试有什么问题是我没有正确地将 json 转换为字典,对吗?感谢您对脚注的帮助!你是我的救星。谢谢!
  • 是的,当然。这就是问题所在。如果有帮助,您可以投票。谢谢:)
猜你喜欢
  • 2019-08-31
  • 1970-01-01
  • 2022-10-01
  • 1970-01-01
  • 2023-03-25
  • 2016-12-18
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多