加载中…
个人资料
Mikasa_mm
Mikasa_mm
  • 博客等级:
  • 博客积分:0
  • 博客访问:794
  • 关注人气:2
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Python unicode转换成dict格式

(2017-04-03 15:06:31)
标签:

python

json

unicode

dict

header

分类: 计算机
问题情景:从excel里读取的json内容是unicode编码的,如果直接使用其当http请求的header会报错:'unicode' object has no attribute 'items' ,必须转化成dict模式才会被识别。

解决方法:
将unicode通过函数.encode('gbk')转化成str类型,再通过json.loads(str)/simplejson.loas(str)转化成dict
1.simplejson.loas(str)
典型的 JSON 格式,使用simplejson把JSON转化为Python内置类型
可以这样使用:
JSON到字典转化:
ret_dict = simplejson.loads(json_str)    --需要pip install 并 import simplejson
字典到JSON转化:
json_str = simplejson.dumps(dict)    

举例:

def get_header(num):
#print "get_header_list()[num]:",get_header_list()[num]  --unicode格式的
header = get_header_list()[num].encode('gbk')
header = simplejson.loads(header)
#header = json.loads(header)
print "header:",header
print "type(header):",type(header)
return header

效果:
header: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer 9af0b988-496c-46cb-9785-2c0838931127'}
type(header):

2.json.loads(str)
直接str = json.loads(str)    --需要import json

效果:
header: {u'Content-Type': u'application/x-www-form-urlencoded', u'Authorization': u'Bearer 9af0b988-496c-46cb-9785-2c0838931127'}
type(header):



这两种header都可以被识别,接下来可以成功获取status_code了:

def set_headers(self):
headers = rw_excel.get_header(2)    # rw_excel是我自己定义的文件
print "headers:",headers
return headers
def get_status_code(self):
status_code = requests.get(url=self.set_url(),headers=self.set_headers()).status_code
print "status_code:",status_code
return status_code


注,如果遇到报错:
simplejson.scanner.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
原因是读取的excel里unicode header里是用的单引号,无法转成json格式;双引号{"key":"value","key2":"value2"}这种格式的才可以转。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有