python 处理 {'message': 'JSON parse error - Expecting value: line 1 column 1 (char 0)', 'code': 'parse_error'}
今天在运行自动化的过程中,遇到了 {'message': 'JSON parse error - Expecting value: line 1 column 1 (char 0)', 'code': 'parse_error'}这个的error,各种尝试无果:
请求的数据为json格式:
data = {'code_type': 'send', 'category': 1, 'phone': '13123456784'}
发送请求:requests.post(url,data)
返回结果:{'message': 'JSON parse error - Expecting value: line 1 column 1 (char 0)', 'code': 'parse_error'}
之前遇到过,尝试把json格式的数据转换为string,就解决了,今天怎么处理都不行,没法了,向万能的度娘求助,终于解决:
借助第三方包的帮助,这里使用了demjson的包来处理这个问题
安装: pip install demjson
使用: demjson.encode(data)
demjson有两个主要的方法:
- encode 编码,将对象转换为json
- decode 解码,将json转化为对象
python单元测试
import json import random import uuid import demjson from django.test import TestCase from rest_framework.test import APIClient from back_server.models import CertificationSource class LittleTestCase(TestCase): def setUp(self): self.client = APIClient() self.test_cs = CertificationSource.objects.create(**{"id":uuid.uuid1(node=random.randint(0,281474976710655)) ,"cs_name": "ni_ldap_test00", "hosts": "LDAP://navinfo.ldap.com;LDAPS://navinfo.ldap.com", "base_dn": "OU=ww,DC=aa,DC=ss", "user_filter": "dsdsdfa", "remark": "test", "user_cn": "CN=users,OU=xx,DC=xx,DC=com", "state": False}) self.test_cs1 = CertificationSource.objects.create(**{"id":uuid.uuid1(node=random.randint(0,281474976710655)), "cs_name": "ni_ldap_test08", "hosts": "LDAP://navinfo.ldap.com;LDAPS://navinfo.ldap.com", "base_dn": "OU=ww,DC=aa,DC=ss", "user_filter": "dsdsdfa", "remark": "test", "user_cn": "CN=users,OU=xx,DC=xx,DC=com", "state": False}) self.test_cs2 = CertificationSource.objects.create(**{"id": uuid.uuid1(node=random.randint(0, 281474976710655)), "cs_name": "ni_ldap_test09", "hosts": "LDAP://navinfo.ldap.com;LDAPS://navinfo.ldap.com", "base_dn": "OU=ww,DC=aa,DC=ss", "user_filter": "dsdsdfa", "remark": "test", "user_cn": "CN=users,OU=xx,DC=xx,DC=com", "state": False}) def test_batch_delete_cs(self): cs_id_list= [str(self.test_cs2.id),str(self.test_cs1.id)] print(cs_id_list,'cs_id_list') import demjson last_cs_id_list=demjson.encode(cs_id_list) print(cs_id_list,'idlis_json----',type(cs_id_list),'type====') r = self.client.post(path="/iam/api/v1/batch/certification?option=" + "delete", data=last_cs_id_list,content_type='application/json') result = r.json() self.assertEqual(result['result']['data']['delete_success_list'], cs_id_list)
打印结果
['2963f0c6-5cf2-11ea-beb1-a93aec2284b4', '2963c8e6-5cf2-11ea-9a9c-863031c2bb23'] cs_id_list ['2963f0c6-5cf2-11ea-beb1-a93aec2284b4', '2963c8e6-5cf2-11ea-9a9c-863031c2bb23'] idlis_json---- <class 'list'> type====