简体   繁体   中英

Python JSON encoding invalid json format

i've stucked, i have a json with symbols like ' in values and syntax with ' and "

Example mix double qoute and single qoute link

json ={
 'key': "val_'_ue",
 'secondkey': 'value'
}

With json loads and json dumps i got a str type not a dict to iterate, any ideas how i get it fixed?

        print(postParams)# = {'csrf-token': "TOKEN_INCLUDES_'_'_symbols", 'param2': 'params2value'}

        jsn_dict2 = json.loads(json.dumps(postParams))
        print(type(jsn_dict2)) # ERROR HERE why str and not dict
        
        for key, val in jsn_dict2.items():
            print("key="+str(key))

you dont need to dumps() an already string json data:

jsn_dict = json.loads(json.dumps(res)) 

should be :

jsn_dict = json.loads(res) 

UPDATE

according to comments the data is looks like so:

postParams = "{'csrf-token': \"TOKEN_INCLUDES_'_'_symbols\", 'add-to-your-blog-submit-button': 'add-to-your-blog-submit-button'}"

so i found an library that can help damaged json string like this one:

  • first run :

    pip install demjson

  • then this code can help you:

from demjson import decode
data = decode(postParams)
data
>>> {'csrf-token': "TOKEN_INCLUDES_'_'_symbols",
 'add-to-your-blog-submit-button': 'add-to-your-blog-submit-button'}

In your json u have missed the "," comma separation between two keys. The actual structure of the JSON is

json_new ={ 'key': "val_'_ue", 'secondkey': 'value' }

use

json_actual=json.dumps(json_new)

to read,

json_read=json.loads(json_actual)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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