标签:字符串 imp 内存 模拟 utf-8 转换 生成 highlight 代码
Json
不同平台(一般是不同的语言)之间进行数据交换
vim day6-1.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
import json
name = {
‘alex‘:[22,‘M‘],
‘rain‘:[21,‘F‘]
}
name_after_transfer = json.dumps(name)
print name
print name_after_transfer

好像没什么区别单引号变成双引号了,json其实是把字典转换成为了字符串
在看以下列子
vim day6-2.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
name = {
‘alex‘:[22,‘M‘],
‘rain‘:[21,‘F‘]
}
f = file("data_to_qq.txt","wb")
f.write(name)
f.close()
运行报错,传递必须是字符串或者二进制字符不能是字典

修改代码
#!/usr/bin/python
# -*- coding:utf-8 -*-
import json
name = {
‘alex‘:[22,‘M‘],
‘rain‘:[21,‘F‘]
}
name_after_transfer = json.dumps(name) #使用JSON方法把字典转化成字符串了
f = file("data_to_qq.txt","wb")
f.write(name_after_transfer)
f.close()
#print name
#print name_after_transfer
运行就会生成文件data_to_qq.txt了
模拟调用这个数据文件
vim qq_app.py
import json
f = file("data_to_qq.txt",‘rb‘)
name = json.loads(f.read())
f.close()
print name[‘alex‘]

需要使用json的loads方式在把字符串文件导成字典才能取到值
PS:该功能可以用在不同的程序之间的内存之间传递数据
JSON只能转换常用的数据格式比如字典,字符串,数组,元祖等 不同语言之间的函数定义是不同的,所以不能转换(比如日期格式)
标签:字符串 imp 内存 模拟 utf-8 转换 生成 highlight 代码
原文地址:http://www.cnblogs.com/minseo/p/6857461.html