python - 如何使用 Panda 将 JSON 字符串中的所有元素输出到表中

标签 python json python-3.x pandas

我正在尝试从网页中抓取结果表,并最终将这些结果写入 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 生成):

/image/DTtp2.jpg

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

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

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

最佳答案

下面的代码将字符串字典转换为数据帧。下面的步骤 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

输出:

enter image description here

关于python - 如何使用 Panda 将 JSON 字符串中的所有元素输出到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514826/

相关文章:

java - 解析具有多个 Json 元素且没有逗号分隔的字符串

javascript - Django - 在模板中显示 Json 或 Httpresponse

python - 来自 sqlalchemy 的 psycopg2 register_composite

python - SQLAlchemy:对多列进行排序返回多个值

python - GroupBy 总和作为开始和结束日期范围的比例

python - colorbar 范围 matplotlib python 的问题

javascript - 如何使用jquery获取json所有标签的类名

python - 提取字典中的值

python-3.x - 线性回归决定系数背后的直觉

python - django 中最终用户的动态表单