我正在使用以下代码来解析对熊猫数据框的json响应,然后转换嵌套的json'terms'
示例json:
{
"conditions": [
{
"id": 3855792,
"type": "apm_app_metric",
"name": "Error percentage (2.5%)",
"enabled": true,
"entities": [
"3418936",
"39720385",
"70369692",
"3242026",
"3744556",
"5673838"
],
"metric": "error_percentage",
"condition_scope": "application",
"terms": [
{
"duration": "5",
"operator": "above",
"priority": "critical",
"threshold": "2.5",
"time_function": "any"
}
]
}
]
}
代码:
import requests
import json
import pandas as pd,os
from pandas.io.json.normalize import json_normalize
json_data = json.loads(response.text)
terms_data = json_normalize(data = json_data['conditions'],
record_path = 'terms',
meta = ['condition_scope', 'enabled', 'id', 'metric', 'name', 'type', 'entities'])
但是,该脚本在尝试将“实体”解析到数据框中时失败,并出现以下错误
meta = ['condition_scope', 'enabled', 'id', 'metric', 'name', 'type', 'entities'])
File "C:\Users\M1049639\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\json\normalize.py", line 279, in json_normalize
result[k] = np.array(v).repeat(lengths)
File "C:\Users\M1049639\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 3119, in __setitem__
self._set_item(key, value)
File "C:\Users\M1049639\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 3194, in _set_item
value = self._sanitize_column(key, value)
File "C:\Users\M1049639\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 3391, in _sanitize_column
value = _sanitize_index(value, self.index, copy=False)
File "C:\Users\M1049639\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\series.py", line 4001, in _sanitize_index
raise ValueError('Length of values does not match length of ' 'index')
ValueError: Length of values does not match length of index
所需的输出: output
最终输出: output