【问题标题】:Mapping csv file to nested json将 csv 文件映射到嵌套的 json
【发布时间】:2017-02-28 01:55:55
【问题描述】:

我有 csv 格式的数据

"category1", 2010, "deatil1"
"category1", 2010, "deatil2"
"category1", 2011, "deatil3"
"category2", 2011, "deatil4"

我需要以

的形式将它映射到json
 {
        "name": "Data",
        "children": [{
            "name": "category1",
            "children": [{
                "name": "2010",
                "children": [
                    {"name": "deatil1"}, 
                    {"name": "detail2"}
                 ],
                "name": "2011",
                "children": [
                    {"name": "detail3"}
                ]
            }, {
            }]
        }, 
            {
            "name": "category2",
            "children": [{
                    "name": "2011",
                    "children": [{
                        "name": "detail4"
                    }]
                }
            ]
        }
    ]
    }

基本上我需要收集每个独特类别和年份对的所有详细信息并列出

我尝试使用嵌套的dict结构,但输出不正确。

我创建了一个自定义字典类来处理字典的嵌套。以下代码以正确的结构收集数据,但我不确定如何继续以正确的格式输出数据。任何帮助将不胜感激。

class Vividict(dict):

    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

dict = Vividict()

for row in ws.iter_rows(row_offset=1):
    sector = row[0].value
    year =  row[2].value
    detail = row[1].value
    dict[sector][year][detail]

print json.dumps(dict).encode('utf8')

【问题讨论】:

    标签: python json csv dictionary


    【解决方案1】:

    从您的dict 结构开始,构建新的数据结构。我在这里主要使用创建dict 的列表推导:

    import json
    
    rows = [
        ("category1", 2010, "deatil1"),
        ("category1", 2010, "deatil2"),
        ("category1", 2011, "deatil3"),
        ("category2", 2011, "deatil4")]
    
    class Vividict(dict):
        def __missing__(self, key):
            value = self[key] = type(self)()
            return value
    
    dict = Vividict()
    
    for row in rows:
        sector = row[0]
        year = row[1]
        detail = row[2]
        dict[sector][year][detail]
    
    # This is the new data structure, derived from the existing 'dict'
    d = {'name': 'Data',
         'children': [
             {'name': k1,  # sector
              'children': [
                           {'name': k2,  # year
                            'children': [
                                {
                                 'name': k3  # deatil
                                 } for k3 in v2.keys()]
                            } for k2, v2 in v1.iteritems()]
              } for k1, v1 in dict.iteritems()]
         }
    
    print json.dumps(d).encode('utf8')
    

    在此处查看实际操作:https://eval.in/662805

    【讨论】:

    • 其实你是在使用字典推导!
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2020-03-19
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2020-09-01
    相关资源
    最近更新 更多