json用法

主要为四个方法:

load: load from file

loads: 'loads' from string:

dump: dump to file

dumps: dumps to string:


#/usr/bin/python
import json

#'loads' from string:
s1 = '{"2name":"testdict", "3a":{"name":"seq", "parameter":["1", "2"]}}'
j1 = json.loads(s1)
print 'j1 type:',type(j1)
print j1
print 

# dumps to string:
s2 = json.dumps(j1)
print 's2 type:',type(s2)
print s2
print 

# dump to file
f1 = open('f1.json','w')
json.dump(j1,f1,sort_keys=True,indent=4)
f1.close()

# load from file
f2 = open('f1.json')
j2 = json.load(f2)
print 'j2 type:',type(j2)
print j2
print 

# change from dict
dic = {"2name":"testdict", "1":{"name":"seq", "parameter":["1", "2"],'zjltest':('10','3','45')}}
print 'dic type:',type(dic)
print 'dic is:',dic
print 'dic["1"]["zjltest"] type is:',type(dic['1']["zjltest"])
s_dic = json.dumps(dic)
print "s_dic type:",type(s_dic)
print "s_dic is:",s_dic
j_dic = json.loads(s_dic)
print "j_dic type:",type(j_dic)
print "j_dic is:",j_dic
print 'j_dic["1"]["zjltest"] type is:',type(j_dic['1']["zjltest"])

输出为:

j1 type: <type 'dict'>
{u'2name': u'testdict', u'3a': {u'parameter': [u'1', u'2'], u'name': u'seq'}}


s2 type: <type 'str'>
{"2name": "testdict", "3a": {"parameter": ["1", "2"], "name": "seq"}}


j2 type: <type 'dict'>
{u'2name': u'testdict', u'3a': {u'parameter': [u'1', u'2'], u'name': u'seq'}}


dic type: <type 'dict'>
dic is: {'1': {'zjltest': ('10', '3', '45'), 'parameter': ['1', '2'], 'name': 'seq'}, '2name': 'testdict'}
dic["1"]["zjltest"] type is: <type 'tuple'>
s_dic type: <type 'str'>
s_dic is: {"1": {"zjltest": ["10", "3", "45"], "parameter": ["1", "2"], "name": "seq"}, "2name": "testdict"}
j_dic type: <type 'dict'>
j_dic is: {u'1': {u'zjltest': [u'10', u'3', u'45'], u'parameter': [u'1', u'2'], u'name': u'seq'}, u'2name': u'testdict'}
j_dic["1"]["zjltest"] type is: <type 'list'>


其中,json格式在python中保存为dict格式。但dict格式向json转换时,有些格式json并不兼容,会发生转化。如:元组tuple会转换为list格式。

你可能感兴趣的:(json用法)