【问题标题】:Nested JSON file flattened and stored as CSV嵌套的 JSON 文件展平并存储为 CSV
【发布时间】:2017-08-02 14:07:44
【问题描述】:

我正在尝试将 json 文件转换为 csv 格式,这是 json 文件的 sn-p (sample3.json):

{
  "x" : {
    "-tst1" : {
      "da" : "8C",
      "d" : "df4",
      "h" : 0,
      "i" : 1,
      "s" : false,
      "t" : 1501394756245
    },
    "-tst2" : {
      "da" : "8C",
      "d" : "\\df&*",
      "h" : 0,
      "i" : 0,
      "s" : true,
      "t" : 1501394946296
    }
  }   
}

这些是我尝试过的一些解决方案,但我无法让它们中的任何一个起作用: Convert list into a pandas data frame DataFrame from list of list Convert Nested JSON to Excel using Python

我怎样才能得到一张像下面这样可以导出到 csv 的表格?

Table

我尝试了几种不同的方法,但我没有得到任何结果......我得到的最远的方法是将值放入列表中。

这似乎很简单,但我更像是一个 sql 人而不是 python。

感谢您的帮助。

import json
import ast
import pandas as pd
from pprint import pprint
from pandas.io.json import json_normalize
import itertools
from openpyxl import load_workbook
import openpyxl
from collections import Counter


test = open('sample3.json').read()
data = json.loads(test)
vals = data['x']

for key in vals.keys():
    v = vals.values
    t = list(vals.values())
    #pd.DataFrame(t)
#print(type(t)) 
#print('Separator')
#print(type(v))  




df = pd.DataFrame.from_items(t)  #error:  Not enough values to unpack...expected 2, got 1.
print(df)

【问题讨论】:

标签: python


【解决方案1】:

我不确定你想要什么,但这对你有用吗?

import json
import pandas as pd

with open('sample3.json') as f: # this ensures opening and closing file
    a = json.loads(f.read())

data = a["x"]

df = pd.DataFrame(data)

print(df.transpose())

我的输出:

          d  da  h  i      s              t
-tst1   df4  8C  0  1  False  1501394756245
-tst2  df&*  8C  0  0   True  1501394946296

你可以这样做:

df.transpose().to_csv('myfilename.csv')

针对您的评论,您可以:

import json
import pandas as pd

a = """{"z" : { "y" : { "x" : { "-v" : { "d1" : "8C:F", "d2" : "8.0", "t" : 3, "x" : 45 }, "-u" : { "d1" : "8C", "d2" : "8.00", "t" : 5, "x" : 45 } } } }}"""

js = json.loads(a)

print pd.DataFrame.from_dict(js['z']['y']['x'], orient='index')

(您发布的 json 缺少 },但我认为这是复制/粘贴错误)

【讨论】:

  • 是的!太棒了。正是我想要的……这会有效地扩展到大型数据集吗?
  • 对于“大”和“高效”的某些值,是的。 :)
  • 我可以麻烦您寻求更多帮助吗?我有第二个这样的 json 文件 ` {"z" : { "y" : { "x" : { "-v" : { "d1" : "8C:F", "d2" : "8.0", " t”:3,“x”:45 },“-u”:{“d1”:“8C”,“d2”:“8.00”,“t”:5,“x”:45 } } } } ` 你给的脚本可以修改成这种文件格式吗?
  • @Gee 你必须取消嵌套 - 我会将代码添加到我的答案中
猜你喜欢
  • 2020-01-21
  • 2020-03-08
  • 1970-01-01
  • 2021-07-02
  • 2021-05-14
  • 2012-04-15
  • 1970-01-01
  • 2016-10-06
  • 2021-09-05
相关资源
最近更新 更多