【问题标题】:How to output all elements in a JSON string to a table using Panda如何使用 Panda 将 JSON 字符串中的所有元素输出到表中
【发布时间】:2019-08-26 03:27:00
【问题描述】:

我正在尝试从网页中抓取结果表,并最终将这些结果写入 csv 文件。我已经使用 BeautifulSoup 抓取页面,提取包含我需要的数据的 JSON 字符串并让 Pandas 输出该表,但它似乎只是打印表轮廓,而不包含任何行详细信息。

我的代码如下(这可能表明它对编程非常陌生!):

from bs4 import BeautifulSoup
import urllib3
import json
import pandas as pd
from pandas.io.json import json_normalize
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
http = urllib3.PoolManager()
url = '[url_im_scraping]'
headers = urllib3.util.make_headers(basic_auth='[username/password]')
response = http.request('GET', url, headers=headers)
soup = BeautifulSoup (response.data, 'html.parser')
#This extracts the initial table of data
grid_data = soup.find("script", class_="__allTestPointsOfSelectedSuite")
data = json.loads(grid_data.text)
#This was to remove the column settings part of the table
testtest = grid_data.text.split("testPoints")
#Putting "{" and the initial key back into the string and loading into JSON object
print(pd.read_json("{" + "\"testPoints" + testtest[1]))

当我将我的 JSON 字符串加载到创建网站(如 json2table)的 JSON 表中时,它会正确显示并验证为有效的 JSON 字符串,并输出如下内容:

testpoints
Column1 Column2 Column3 Column4 etc...
totalPointsCount

当我尝试使用 Pandas 将 JSON 字符串输出为表格时,我得到以下信息:

                                           testPoints  totalPointsCount
0   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
1   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
2   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
3   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
4   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
5   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
6   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
7   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
8   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
9   {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
10  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
11  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
12  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
13  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
14  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
15  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17
16  {'assignedTo': 'a5060ed2-6b1c-4da3-add0-0d6d97...                17

我不确定如何在“testPoints”和“totalPoundsCount”这两个键中显示嵌套字段。

我希望如何在此处获取输出的示例(使用 Json2table 生成):

https://imgur.com/YURdRCy

希望有人能指出我出错的正确方向。

编辑:我现在已经更改了最大列宽,并且看到我得到了这样返回的整个字符串:

{'assignedTo': 'a5060ed2', 'automated': 'Not Automated', 'build': None, 'configurationId': 123, 'configurationName': 'Package 1.0', 'lastResultState': 1, 'lastRunBy': '', 'lastRunDuration': 0, 'mostRecentResultOutcome': 2, 'mostRecentRunId': 1234, 'outcome': 'Passed', 'state': 2, 'suiteId': 1234, 'suiteName': Name', 'testCaseId': 12345, 'testPointId': 12345, 'tester': 'Fred Smith', 'workItemProperties': [{'Key': 'System.Id', 'Value': 12345}, {'Key': 'System.Title', 'Value': 'Item Item'}, {'Key': 'System.IterationPath', 'Value': 'Path\Path'}, {'Key': 'System.ChangedDate', 'Value': '/Date(1554200489873)/'}, {'Key': 'System.ChangedBy', 'Value': 'Fred Smith'}, {'Key': 'Microsoft.VSTS.TCM.AutomationStatus', 'Value': 'Not Automated'}]}         

,但我仍在努力解决如何从该字符串中获取“assignedTo”等作为列标题,即:

assignedTo     Automated       Build
123456789      Not Automated   None

【问题讨论】:

    标签: python json python-3.x pandas


    【解决方案1】:

    下面的代码将字符串字典转换为数据帧。下面的步骤 2 可以在整个字符串表上循环。这个循环可能有append() 将所有记录编译到一个数据帧中。

    第 1 步: 在此示例中,将字符串分配给变量:

    df = {'assignedTo': 'a5060ed2', 'automated': 'Not Automated', 'build': None, 'configurationId': 123, 
          'configurationName': 'Package 1.0', 'lastResultState': 1, 'lastRunBy': '', 'lastRunDuration': 0, 
          'mostRecentResultOutcome': 2, 'mostRecentRunId': 1234, 'outcome': 'Passed', 'state': 2, 
          'suiteId': 1234, 'suiteName': 'Name', 'testCaseId': 12345, 'testPointId': 12345, 'tester': 'Fred Smith', 
          'workItemProperties': [{'Key': 'System.Id', 'Value': 12345}, {'Key': 'System.Title', 'Value': 'Item Item'}, 
                                 {'Key': 'System.IterationPath', 'Value': 'Path\Path'}, 
                                 {'Key': 'System.ChangedDate', 'Value': '/Date(1554200489873)/'}, 
                                 {'Key': 'System.ChangedBy', 'Value': 'Fred Smith'}, 
                                 {'Key': 'Microsoft.VSTS.TCM.AutomationStatus', 'Value': 'Not Automated'}]} 
    

    第 2 步:

    将字符串转换为数据框:

    temp = pd.DataFrame({'assignedTo':[df['assignedTo']], 'automated':[df['automated']], 'build':[df['build']]}) 
    temp
    

    输出:

    【讨论】:

    • 我收到以下错误:temp = pd.DataFrame({'assignedTo':[df['assignedTo']], 'automated':[df['automated']], 'build':[df['build']]}) TypeError: string indices must be integers。它似乎期待 df[1] 而不是字符串?
    • 好的,所以我将字符串存储在变量“content3”中。如果我将该变量打印到控制台,然后将输出复制到“DF =”它工作正常,如果我尝试说“DF=content3”,那么我会收到字符串索引错误消息。我不确定它为什么接受它我将该字符串变量的输出复制并粘贴到脚本中,但不会直接接受字符串变量?
    • 啊破解了。我做了 print(type(content3)) 并看到它显示的是字符串类型,但 print(type(df)) 显示的是 dict 类型。做了一些谷歌搜索并尝试了df= json.loads(content3),它将它加载为字典类型而不是字符串,现在一切正常。这对我来说已经足够了,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-06-24
    • 2023-01-14
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2018-06-22
    • 2021-12-18
    相关资源
    最近更新 更多