Python处理JSON

来源:互联网 发布:淘宝装修设计师模块 编辑:程序博客网 时间:2024/06/10 15:36

列表或dict转字符串

import jsondata = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象print "DATA:",repr(data)data_string = json.dumps(data)print "JSON:",data_string

输出:

DATA: [{'a':'A','c':3.0,'b':(2,4)}] #python的dict类型的数据是没有顺序存储的JSON: [{"a":"A","c":3.0,"b":[2,4]}]  

字符串转列表或字典

import jsondata = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象data_string = json.dumps(data)print "ENCODED:",data_stringdecoded = json.loads(data_string)print "DECODED:",decodedprint "ORIGINAL:",type(data[0]['b'])print "DECODED:",type(decoded[0]['b'])

输出:

ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}]DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]ORIGINAL: <type 'tuple'>DECODED: <type 'list'>
0 0
原创粉丝点击