使用Python将元组转换为JSON(Tuples conversion into JSON with python)

360 IT屋

I would like some help converting a tuple in format [(X, Y, Z),(..) of type (string, string, int)] to a JSON file in the format:

{
    "name": "X",
    "children": [{
        "name": "Y",
        "value": Z
    }]
}

I have at least 1M values to convert and at the moment I have attempted using a key for the dictionary:

b = (dict(zip(keys,row)) for row in tuples)  

using the JSON library

print (json.dumps(list(b)))  

however this yields a JSON in the format

[{"type": "y", "name": "z", "count": z},...  

Preferably I would like the Y and Z values to be nested under children and the X value to be used once per unique string.

   {
    "name": "X",
    "children": [{
        "name": "Y",
        "value": Z
    },
                {
        "name": "Y2",
        "value": Z2
    }]
   }
解决方案

Assuming you want a list of dicts as the output of the json with each dict be the form in your question:

The following one liner will put it into the data structure your looking for with each tuple generating it's own complete structure:

[{'name':i[0], 'children': [{'name': i[1], 'value': i[2]}]}  for i in tuples]

But I suspect you want the outer name to be unique with inner children being built from multiple tuples, such that there is only one such structure generated with 'name' == X.

To do it in a memory efficient manner start by sorting your tuples by X:

# should work as long as you aren't doing any fancy sorting
stuples = sorted(tuples) 

name = None
dat = None
for t in stuples:
    if name != t[0]:
        if dat is not None:
            writeDat(json.dumps(dat))
        name = t[0]
        dat = {'name': t[0], 'children': [{'name': t[1], 'value': t[2]}]}
    else:
        dat['children'].append({'name': t1, 'value': t[2]})

I assume you have a function to write one of these out such as writeDat() that takes the json so you aren't storing them all in ram.

我需要一些帮助来转换格式为 [(X,Y,Z),(..)类型为(string,字符串,int)] 格式的JSON文件:



  {
name: X,
children:[{
name: Y,
value:Z
}]
}


我至少有1M个要转换的值,而现在我尝试使用字典的键:



  b =(dict(zip(zip(keys,row)))表示元组中的行)


使用JSON库



  print( json.dumps(list(b)))


但是这会产生

  [{ type: y, name: z, count:z},... 


最好我希望Y和Z值嵌套在子项下,而X值只使用一次每个唯一的字符串。



  {
name: X,
children:[{
名称: Y,
值:Z
},
{
名称: Y2,
值:Z2
}]
}

解决方案

假设您想要一列字典作为json的输出,而每个字典就是您问题中的形式:



以下一行将其放入您的数据结构中寻找每个生成其完整结构的元组:



  [{'name':i [0],'children': [{'name':i [1],'value':i [2]}]}对于元组中的i] 


但是我怀疑您希望外部名称是唯一的,因为内部子项是由多个元组构建的,因此只有一个这样的结构由'name'== X



要以内存有效的方式进行操作,首先需要对元组进行排序X:



 #应该可以工作,只要您不花哨地排序
stuples = sorted(tuples)

name =无
dat =无
for stuples:
如果name!= t [0]:
如果dat不是None:
writeDat(json.dumps(dat))
name = t [0]
dat = {'name':t [0],'children':[{'name':t [1],'value':t [2]}]}
else:
dat ['children']。append({'name':t1,'value':t [2]} )


我假设您有一个函数可以写出其中之一,例如 writeDat()接受json,这样就不会将它们全部存储在ram中。


本文地址:IT屋 » 使用Python将元组转换为JSON