SoFunction
Updated on 2024-12-16

python use json will string to dictionary error resolution

Description of the problem

C:\Users\lenovo\AppData\Local\Programs\Python\Python37\ D:/360MoveData/Users/lenovo/Desktop/startProject/.PAAS_Interface/TestCases/UM/Test_01_register.py
D:\360MoveData\Users\lenovo\Desktop\startProject\.PAAS_Interface\common\
Traceback (most recent call last):
  File "D:/360MoveData/Users/lenovo/Desktop/startProject/.PAAS_Interface/TestCases/UM/Test_01_register.py", line 73, in <module>
    Test_UM_register().test_01()
  File "D:/360MoveData/Users/lenovo/Desktop/startProject/.PAAS_Interface/TestCases/UM/Test_01_register.py", line 52, in test_01
    headers = (dataList[1])
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\json\", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\json\", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Process finished with exit code 1

as above,: Expecting property name enclosed in double quotes

Means jsondecodeerror: expects attribute names to be enclosed in double quotes

Problem analysis

I look at my raw data in the format:

{‘Content-Type': ‘application/json'}

python for single quotes, double quotes are considered quotes, but for json, it recognizes double quotes according to. Therefore, whenever json is used for formatting, single quotes must be converted to double quotes, with "\" escaping when necessary.

By analyzing the above problems, we get two solutions:

  • Replace the original format with double quotes;
  • Convert it the other way around.

Problem solving

1. Replace the original format with double quotes

{‘Content-Type': ‘application/json'}

change into

{“Content-Type”: “application/json”}

Validate the results:

successes

2, change other ways to convert

        headers = eval(dataList[1])
        # headers = (dataList[1])

Validate the results:

successes

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.