json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 问题解决


#今天在练习搭建框架的python测试 框架的时候,使用json.loads解码字符串不能转json对象的问题;
#coding=utf-8 import xlrd,time import configparser, xlrd import requests import logging import sys,json sys.path.append("..\scripts") from method import * cf = configparser.ConfigParser() cf.read("..\configure\config.conf") url1 = cf.get("urls", "url1") print("url-->", url1) xlsx_path = cf.get("testcase", "file") print("xlsx_path-->", xlsx_path) sheet = cf.get("testcase", "Sheet") print("sheet--->", sheet) log_file=cf.get("log","file") logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=log_file, filemode='a') wk = xlrd.open_workbook(xlsx_path) sh = wk.sheet_by_name(sheet) nums = sh.nrows print("nums",nums) for i in range(1, nums): switch = sh.cell(i, 0).value print(switch) # print "ip---------------->",ip api = sh.cell(i, 2).value print(type(api)) method = sh.cell(i, 3).value data = sh.cell(i, 4).value print("data=======\n",data) print("----------------------------") if switch=="open" and api=="getip/" and method=="get": url=url1+api print("url=====>>>>",url) print("data1===",data) data=json.loads(data) print("data2===", data) print(type(data)) r = Get(url,data['ip']) print("r===>",r) logging.info(r[1]) break # print(switch) # if sw=='open': # reponse = get_ip(ip) # print ("reponse--->",reponse) # code=reponse['code'] # print ('code----->',code) # f.write('test_main:%s\n'%code) # if code==3: # f.write('test_result:%s\n'%'pass') # else: # f.write('test_result:%s\n' % 'false') # else: # pass # # # import requests,json#导入EXCEL # # wk=xlrd.open_workbook('test01.xlsx') #打开那个excel # sheet=wk.sheet_by_name('Sheet1') #打开哪张表 # nums=sheet.nrows # # f=open('log_%s.txt'%(time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))),'a') # # f.write("TEST_START".center(20,"*")+'\n') # #reponse= '' # for i in range(1,nums): # sw=sheet.cell(i,0).value # # #print "ip---------------->",ip # ip=sheet.cell(i,2).value # testcase=sheet.cell(i,1).value # if sw=='open': # reponse = get_ip(ip) # print ("reponse--->",reponse) # code=reponse['code'] # print ('code----->',code) # f.write('test_main:%s\n'%code) # if code==3: # f.write('test_result:%s\n'%'pass') # else: # f.write('test_result:%s\n' % 'false') # else: # pass # f.write("TEST_END".center(20,'*')+'\n') # f.close() #

  执行以上代码后;开始报错;

 

为了不影响整体代码运行,字符串不单独列出一个脚本进行测试;

#coding=utf-8
import  requests
import json
header={}
import re
def Get(url,data):
	r=requests.get(url=url,headers=header,params=data)
	return r.status_code,r.text

def Post(url,data):
	r=requests.get(url=url,headers=header,json=data)
	return r.status_code,r.text

url="http://172.31.4.118:5000/getip/"
data="1.1.1.1"
# with open('http://172.31.4.118:5000/getip/1.1.1.1') as jsonfile:
# 	data = json.load(jsonfile)
print(data)



# print(type(Get(url,data).__str__()))
str_st=Get(url,data).__str__()


print("str_str---->",str_st)
# str_st=re.sub('\'','\"',str_st)
# str_st=re.sub("u'","\"",str_st)
#
# str_st = str_st.replace("'", '"');
print(type(str_st))
# string = str_st.replace("u", "")
dict_cc=json.loads(str(str_st))
print(dict_cc)

# print(type(Get(url,data)))

 

查阅相关资料后:

1. 替换单引号

类型的错误,就是由于JSON中,标准语法中,不支持单引号,属性或者属性值,都必须是双引号括起来的。

# str_st = str_st.replace("'", '"');

依旧报同样的错误信息,如下:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
    obj, end = self._scanner.iterscan(s, **kw).next()
  File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
    rval, next_pos = action(m, context)
  File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
    raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)

 

2. 替换引号前的u为空,

即去除引号前的u。这种解决编码问题,简单粗暴了点,至于其深入分析,未完待绪。同时也希望各位大神能够提供更好的解决办法。

# str_st=re.sub("u'","\"",str_st)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM