使用Python将元组转换为JSON [英] Tuples conversion into JSON with python
问题描述
我想要一些帮助,将类型为(string, string, int)]
的类型为[(X, Y, Z),(..)
的元组转换为以下格式的JSON文件:
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
}]
}
我至少有1M个要转换的值,并且现在我尝试使用字典的键:
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)
使用JSON库
print (json.dumps(list(b)))
但是这会产生
[{"type": "y", "name": "z", "count": z},...
最好,我希望Y和Z值嵌套在子项下,而X值每个唯一字符串都使用一次.
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
}]
}
推荐答案
假设您希望将字典列表作为json的输出,而每个字典都是您问题中的形式:
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]
但是我怀疑您希望外部名称在由多个元组构建的内部子代中是唯一的,这样,'name' == X
只能生成一个这样的结构.
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
.
要以节省内存的方式执行此操作,请先将您的元组按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]})
我假设您具有将其中之一写出的功能,例如使用json的writeDat()
,因此您不会将它们全部存储在ram中.
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.
这篇关于使用Python将元组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!