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