嵌套json到csv - 泛型方法

时间:2016-06-08 15:07:19

标签: python json csv pandas

我是Python的新手,我正在努力将嵌套的json文件转换为cvs。为此,我开始加载json,然后使用json_normalize打印出良好输出的方式对其进行转换,然后使用pandas包将标准化部分输出到cvs

我的例子json:

[{
 "_id": {
   "id": "123"
 },
 "device": {
   "browser": "Safari",
   "category": "d",
   "os": "Mac"
 },
 "exID": {
   "$oid": "123"
 },
 "extreme": false,
 "geo": {
   "city": "London",
   "country": "United Kingdom",
   "countryCode": "UK",
   "ip": "00.000.000.0"
 },
 "viewed": {
   "$date": "2011-02-12"
 },
 "attributes": [{
   "name": "gender",
   "numeric": 0,
   "value": 0
 }, {
   "name": "email",
   "value": false
 }],
 "change": [{
   "id": {
     "$id": "1231"
   },
   "seen": [{
     "$date": "2011-02-12"
   }]
 }]
}, {
 "_id": {
   "id": "456"
 },
 "device": {
   "browser": "Chrome 47",
   "category": "d",
   "os": "Windows"
 },
 "exID": {
   "$oid": "345"
 },
 "extreme": false,
 "geo": {
   "city": "Berlin",
   "country": "Germany",
   "countryCode": "DE",
   "ip": "00.000.000.0"
 },
 "viewed": {
   "$date": "2011-05-12"
 },
 "attributes": [{
   "name": "gender",
   "numeric": 1,
   "value": 1
 }, {
   "name": "email",
   "value": true
 }],
 "change": [{
   "id": {
     "$id": "1231"
   },
   "seen": [{
     "$date": "2011-02-12"
   }]
 }]
}]

使用以下代码(此处我排除嵌套部分):

import json
from pandas.io.json import json_normalize


def loading_file():
    #File path
    file_path = #file path here

    #Loading json file
    json_data = open(file_path)
    data = json.load(json_data)
    return data

#Storing avaliable keys
def data_keys(data):
    keys = {}
    for i in data:
        for k in i.keys():
            keys[k] = 1

    keys = keys.keys()

#Excluding nested arrays from keys - hard coded -> IMPROVE
    new_keys = [x for x in keys if
    x != 'attributes' and
    x != 'change']

    return new_keys

#Excluding nested arrays from json dictionary
def new_data(data, keys):
    new_data = []
    for i in range(0, len(data)):
        x = {k:v for (k,v) in data[i].items() if k in keys }
        new_data.append(x)
    return new_data

 def csv_out(data):
     data.to_csv('out.csv',encoding='utf-8')

def main():
     data_file = loading_file()
     keys = data_keys(data_file)
     table = new_data(data_file, keys)
     csv_out(json_normalize(table))

main()

我当前的输出看起来像这样:

| _id.id | device.browser | device.category | device.os |  ... | viewed.$date |
|--------|----------------|-----------------|-----------|------|--------------|
| 123    | Safari         | d               | Mac       | ...  | 2011-02-12   |
| 456    | Chrome 47      | d               | Windows   | ...  | 2011-05-12   |
|        |                |                 |           |      |              |

我的问题是我想将嵌套数组包含到cvs中,所以我必须将它们展平。我无法弄清楚如何使它成为通用的,因此我在创建表时不使用字典keysnumeric, id, name)和values。我必须使其具有普遍性,因为attributeschange中的键数。因此,我希望输出如下:

| _id.id | device.browser | ... | attributes_gender_numeric | attributes_gender_value | attributes_email_value | change_id | change_seen |
|--------|----------------|-----|---------------------------|-------------------------|------------------------|-----------|-------------|
| 123    | Safari         | ... | 0                         | 0                       | false                  | 1231      | 2011-02-12  |
| 456    | Chrome 47      | ... | 1                         | 1                       | true                   | 1231      | 2011-02-12  |
|        |                |     |                           |                         |                        |           |             |

提前谢谢!任何提示如何改进我的代码并使其更高效是非常受欢迎的。

4 个答案:

答案 0 :(得分:4)

感谢Amir Ziai撰写的精彩博文,您可以找到here我设法以平面表的形式输出数据。具有以下功能:

path

我知道由于名称if if语句,它不是完全一般化的。但是,如果删除了创建名称 - 值字典的此豁免,则代码可以与其他嵌入式数组一起使用。

答案 1 :(得分:0)

几周前,我有一个任务将带有嵌套键和值的json转换为csv文件。对于此任务,必须正确处理嵌套键,以将用作要用作值的唯一标头的串联。结果是下面的代码,也可以在here中找到。

def get_flat_json(json_data, header_string, header, row):
    """Parse json files with nested key-vales into flat lists using nested column labeling"""
    for root_key, root_value in json_data.items():
        if isinstance(root_value, dict):
            get_flat_json(root_value, header_string + '_' + str(root_key), header, row)
        elif isinstance(root_value, list):
            for value_index in range(len(root_value)):
                for nested_key, nested_value in root_value[value_index].items():
                    header[0].append((header_string +
                                      '_' + str(root_key) +
                                      '_' + str(nested_key) +
                                      '_' + str(value_index)).strip('_'))
                    if nested_value is None:
                        nested_value = ''
                    row[0].append(str(nested_value))
        else:
            if root_value is None:
                root_value = ''
            header[0].append((header_string + '_' + str(root_key)).strip('_'))
            row[0].append(root_value)
    return header, row

这是基于经济学家对此问题的回答的一种更通用的方法。

答案 2 :(得分:0)

下面的代码处理了一个杂乱的json文件 字典和列表相互之间有 7 层深:

    import csv, json, os
    def parse_json(data):
        a_dict_accum = {}
        for key, val in data.items():
            print("key, val = ", key, val)
            output.writerow([key])
            output.writerow([val])
            if isinstance(val, dict):
                for a_key, a_val in val.items():
                    print("a_key, a_val = ", a_key, a_val)
                    output.writerow([a_key])
                    output.writerow([a_val])
                    a_dict_accum.update({a_key:a_val})
                print("a_dict_accum = ", a_dict_accum)
                parse_json(a_dict_accum)
            elif isinstance(val, list):
                print("val_list = ", val)
                for a_list in val:
                     print("a_list = ", a_list)
                     output.writerow([a_list])
                     if isinstance(a_list, dict):
                         for a_key, a_val in a_list.items():
                             print("a_key, a_val = ", a_key, a_val)
                             output.writerow([a_key])
                             output.writerow([a_val])    
                             a_dict_accum.update({a_key:a_val})
                         print("a_dict_accum = ", a_dict_accum)
                         parse_json(a_dict_accum)
    os.chdir('C://Users/Robert/viirs/20200217_output')
    fileInput = 'night_lights_points.json'
    fileOutput = 'night_lights_points.csv'
    inputFile = open(fileInput) #open json file
    outputFile = open(fileOutput, 'w', newline='') #load csv file
    data = json.load(inputFile) #load json content
    output = csv.writer(outputFile) #create a csv.writer
    output = parse_json(data)
    inputFile.close() #close the input file
    outputFile.close() #close the output file       
                
            

答案 3 :(得分:-2)

使用pandas(在控制台中运行“ pip install pandas ”),2行代码:

import pandas

json = pandas.read_json('2.json')
json.to_csv('1.csv')