Python Tuple转换为JSON [英] Python Tuple to dict to JSON

查看:112
本文介绍了Python Tuple转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据

(('check_kvserver_mem_4500000', 2737L), 
 ('check_ethstatus', 250L), 
 ('check_ddos', 229L), 
 ('check_coredump', 193L),
 ('check_robot', 174L),
 ('check_disk_90_95', 155L))

进入此:打印json.dumps(data)

[["check_kvserver_mem_4500000", 2737], 
 ["check_ethstatus", 250],
 ["check_ddos", 229],
 ["check_coredump", 193], 
 ["check_disk_90_95", 155]]

我想要类似的数据

{["check_kvserver_mem_4500000", 2737],
 ["check_ethstatus", 250]
 ["check_ddos", 229], 
 ["check_coredump", 193], 
 ["check_disk_90_95", 155]}

 {"check_kvserver_mem_4500000":2737,
  "check_ethstatus":250,
  "check_ddos":229, 
  "check_coredump":193,
  "check_disk_90_95":155}

推荐答案

您想要一个JSON对象作为结果,但是您的数据没有键/值结构.因此, json.dumps(data)在生成JSON列表而不是对象方面做得正确.无法在无效的JSON对象上匹配Python元组元组.

You want a JSON Object as a result but your data has no key/value structure. So json.dumps(data) is doing the right thing in generating a JSON List, not an Object. A Python tuple of tuples can not be matched on an invalid JSON Object.

修改

更改问题后(并在执行此操作时删除了我的美丽编辑),您的问题就可以得到答案.

After you changed your question (and deleted my beautiful edits while doing this), your question can be answered.

data = (('check_kvserver_mem_4500000', 2737L),
        ('check_ethstatus', 250L),
        ('check_ddos', 229L),
        ('check_coredump', 193L),
        ('check_robot', 174L),
        ('check_disk_90_95', 155L))
print json.dumps(dict(data))

结果是:

'{"check_disk_90_95": 155, "check_coredump": 193, "check_robot": 174,
  "check_kvserver_mem_4500000": 2737, "check_ddos": 229, "check_ethstatus": 250}'

这篇关于Python Tuple转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆