1

我正在尝试转换一个看起来像的 Json 文件

{
#   "item_1":"value_11",
#   "item_2":"value_12",
#   "item_3":"value_13",
#   "item_4":["sub_value_14", "sub_value_15"],
#   "item_5":{
#       "sub_item_1":"sub_item_value_11",
#       "sub_item_2":["sub_item_value_12", "sub_item_value_13"]
#   }
# }

看起来像这样的东西:

 {
#   "node_item_1":"value_11",
#   "node_item_2":"value_12",
#   "node_item_3":"value_13",
#   "node_item_4_0":"sub_value_14", 
#   "node_item_4_1":"sub_value_15",
#   "node_item_5_sub_item_1":"sub_item_value_11",
#   "node_item_5_sub_item_2_0":"sub_item_value_12",
#   "node_item_5_sub_item_2_0":"sub_item_value_13"
# }

我知道您在转换为 CSV 时无法维护 Json 文件的顺序。我正在考虑通过将 JSON 数据加载到 OrderedDic 对象中来解决问题(这会导致按照输入文档列出它们的顺序添加它们。但是,我是使用 JSON 文件以及 OrderedDic 函数的新手。

要将项目分成我使用的子组:

def reduce_item(key, value):
        global reduced_item

        #Reduction Condition 1
        if type(value) is list:
            i=0
            for sub_item in value:
                reduce_item(key+'_'+to_string(i), sub_item)
                i=i+1

        #Reduction Condition 2
        elif type(value) is dict:
            sub_keys = value.keys()
            for sub_key in sub_keys:
                reduce_item(key+'_'+to_string(sub_key), value[sub_key])

        #Base Condition
        else:
            reduced_item[to_string(key)] = to_string(value)

但是如何使用 orderedDic 和上面的代码来显示这个输出:

{
    #   "node_item_1":"value_11",
    #   "node_item_2":"value_12",
    #   "node_item_3":"value_13",
    #   "node_item_4_0":"sub_value_14", 
    #   "node_item_4_1":"sub_value_15",
    #   "node_item_5_sub_item_1":"sub_item_value_11",
    #   "node_item_5_sub_item_2_0":"sub_item_value_12",
    #   "node_item_5_sub_item_2_0":"sub_item_value_13"
    # }

我也有以下代码,但它不会根据上面的子串代码的条件将每个代码分成子组:

import json
from  collections import OrderedDict
with open("/home/file/official.json", 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)
print(metrics_types)

这表明:

在此处输入图像描述

有什么建议么?

4

1 回答 1

1

您可以使用一个函数来遍历给定的 dict 或列表项,并合并递归调用的 dict 输出中的键:

def flatten(d):
    if not isinstance(d, (dict, list)):
        return d
    out = {}
    for k, v in d.items() if isinstance(d, dict) else enumerate(d):
        f = flatten(v)
        if isinstance(f, dict):
            out.update({'%s_%s' % (k, i): s for i, s in f.items()})
        else:
            out[k] = f
    return out

所以给出:

d = {
  "item_1":"value_11",
  "item_2":"value_12",
  "item_3":"value_13",
  "item_4":["sub_value_14", "sub_value_15"],
  "item_5":{
      "sub_item_1":"sub_item_value_11",
      "sub_item_2":["sub_item_value_12", "sub_item_value_13"]
  }
}

flatten(d)返回:

{'item_1': 'value_11',
 'item_2': 'value_12',
 'item_3': 'value_13',
 'item_4_0': 'sub_value_14',
 'item_4_1': 'sub_value_15',
 'item_5_sub_item_1': 'sub_item_value_11',
 'item_5_sub_item_2_0': 'sub_item_value_12',
 'item_5_sub_item_2_1': 'sub_item_value_13'}

以上假设您使用的是 Python 3.7 或更高版本,其中保证 dict 键是有序的。如果您使用的是早期版本,则可以使用OrderedDict代替常规 dict。

于 2019-03-20T17:38:29.160 回答