简体   繁体   English

Python:JSON 错误:语法错误,格式错误 JSON

[英]Python : JSON Error: Syntax error, malformed JSON

My Python code, which I obtained from POSTMAN, throws an error with the string我从 POSTMAN 获得的 Python 代码在字符串中引发错误

"code":"E101","message":"JSON Error: Syntax error, malformed JSON"}" "code":"E101","message":"JSON 错误:语法错误,JSON 格式错误"}"

although in POSTMAN, the request was successful and produced the expected JSON result.尽管在 POSTMAN 中,请求成功并产生了预期的 JSON 结果。

below is my python code下面是我的 python 代码

import requests

url = "APIURL"

payload={'data': '{
    "authenticate":{
        "apikey":"ABCSHF"
    },
    "services":[
        {
            "call":"history/API",
            "identifier":{
                "search":"desc"
            }
        }
    ]
}'}
files=[

]
headers = {

}

response = requests.request("POST", url, headers=headers, json=payload, files=files)

print(response.text)

Can anyone please help me on this.谁能帮我解决这个问题。

I guess you should get clearness what did you code;):我想你应该清楚你的代码是什么;):

requests parse a dict to a JSON internally, see explanation here requests在内部将 dict 解析为 JSON,请参阅 此处的说明

import json
from pprint import pprint

# some JSON string:
json_string = '{ "authenticate":{ "apikey":"ABCSHF" }, "services":[ { "call":"history/API", "identifier":{ "search":"desc" } } ] }'

# parse JSON string to dict:
json_as_dict = json.loads(json_string)

pprint(json_as_dict)
# >> {'authenticate': {'apikey': 'ABCSHF'},
# >>  'services': [{'call': 'history/API', 'identifier': {'search': 'desc'}}]}

incorrect_payload_as_dict = {'data': json.dumps(json_as_dict)}

pprint(incorrect_payload_as_dict)
# >> {'data': '{"authenticate": {"apikey": "ABCSHF"}, "services": [{"call": '
# >>          '"history/API", "identifier": {"search": "desc"}}]}'}

correct_payload_as_dict = {'data': json_as_dict}

pprint(correct_payload_as_dict)
# >> {'data': {'authenticate': {'apikey': 'ABCSHF'},
# >>          'services': [{'call': 'history/API',
# >>                         'identifier': {'search': 'desc'}}]}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM