将CSV列转换为json中的嵌套字段

时间:2019-10-21 10:58:13

标签: python json pandas csv

我有一个csv文件,其中一些作为x; y; z格式的列。我正在使用熊猫读取此数据,进行一些预处理并使用熊猫的to_json / to_dict方法转换为json对象列表。在转换这些特殊列时,该列的json对象应采用{x:{y:{z:value}}}的格式。可能会有不同的列,例如x:y:z和x:y:a,这2列必须合并在一起,形成格式为{x:{y:{z:value1, a:value2}}}

CSV:

Id,Name,X;Y;Z,X;Y;A,X;B;Z
101,Adam,1,2,3
102,John,4,5,6
103,Sara,7,8,9

输出:

[ 
   { 
      "Id":101,
      "Name":"Adam",
      "X":{ 
         "Y":{ 
            "Z":1,
            "A":2
         },
         "B":{ 
            "Z":3
         }
      }
   },
   { 
      "Id":102,
      "Name":"John",
      "X":{ 
         "Y":{ 
            "Z":4,
            "A":5
         },
         "B":{ 
            "Z":6
         }
      }
   },
   { 
      "Id":103,
      "Name":"Sara",
      "X":{ 
         "Y":{ 
            "Z":7,
            "A":8
         },
         "B":{ 
            "Z":9
         }
      }
   }
]

1 个答案:

答案 0 :(得分:1)

我发现使用pandas将数据作为dict转储会更容易,然后使用递归函数来遍历键,并且在遇到包含;的键的情况下,我用此分隔符将键拆分为递归地创建嵌套的字典。当我到达分割键中的最后一个元素时,我会用原始值更新键,然后从dict中删除原始键。

import pandas as pd
from io import StringIO
import json

def split_key_to_nested_dict(original_dict, original_key, nested_dict, nested_keys):
    if nested_keys[0] not in nested_dict:
        nested_dict[nested_keys[0]] = {}
    if len(nested_keys) == 1:
        nested_dict[nested_keys[0]] = original_dict[original_key]
        del original_dict[original_key]
    else:
        split_key_to_nested_dict(original_dict, original_key, nested_dict[nested_keys[0]], nested_keys[1:])


csv_data = StringIO("""Id,Name,X;Y;Z,X;Y;A,X;B;Z
101,Adam,1,2,3
102,John,4,5,6
103,Sara,7,8,9""")
df = pd.DataFrame.from_csv(csv_data)
df.insert(0, df.index.name, df.index)
dict_data = df.to_dict('records')

for data in dict_data:
    keys = list(data.keys())
    for key in keys:
        if ';' in key:
            nested_keys = key.split(';')
            split_key_to_nested_dict(data, key, data, nested_keys)
print(json.dumps(dict_data))

输出

[{"Id": 101, "Name": "Adam", "X": {"Y": {"Z": 1, "A": 2}, "B": {"Z": 3}}}, {"Id": 102, "Name": "John", "X": {"Y": {"Z": 4, "A": 5}, "B": {"Z": 6}}}, {"Id": 103, "Name": "Sara", "X": {"Y": {"Z": 7, "A": 8}, "B": {"Z": 9}}}]

格式化输出

[
  {
    "Id": 101,
    "Name": "Adam",
    "X": {
      "Y": {
        "Z": 1,
        "A": 2
      },
      "B": {
        "Z": 3
      }
    }
  },
  {
    "Id": 102,
    "Name": "John",
    "X": {
      "Y": {
        "Z": 4,
        "A": 5
      },
      "B": {
        "Z": 6
      }
    }
  },
  {
    "Id": 103,
    "Name": "Sara",
    "X": {
      "Y": {
        "Z": 7,
        "A": 8
      },
      "B": {
        "Z": 9
      }
    }
  }
]