python元组转化为json数据_使用Python将元组转换为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

}]

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值