【发布时间】:2019-06-06 07:14:56
【问题描述】:
我有一个脚本,它将嵌套的 JSON 读取为 pandas 数据框,并向其中添加一个新列并将其另存为 JSON。
import numpy as np
from pandas.io.json import json_normalize
sample_json = {
"name": {
"emails": [{"address": "clark.kent@example.com"}],
"countries": [{"country": "US"}, {"country": "UK"}],
}
}
df = json_normalize(sample_json)
df["name.hobbies"] = np.nan
print(df)
df.to_json("sample.json", orient="records", lines=True)
我的输出看起来像,
{
"name.countries": [
{
"country": "US"
},
{
"country": "UK"
}
],
"name.emails": [
{
"address": "clark.kent@example.com"
}
],
"name.hobbies": null
}
我想将数据框保存为嵌套的 JSON,就像这样,
"name": {
"emails": [{"address": "clark.kent@example.com"}],
"countries": [{"country": "US"}, {"country": "UK"}],
"hobbies": null
}
有没有办法将派生自的 pandas 数据帧保存为嵌套 JSON?
【问题讨论】: