简体   繁体   中英

How can I convert a string response to a valid JSON?

Hi I am trying to convert a string response to a valid json list of objects in python.

value= "{ActionSuccess=True; AdditionalActionsBitMask=0},{ActionSuccess=True; AdditionalActionsBitMask=0}"

I tried json.loads but I got the error json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

I tried to convert using regex but it only return the first object.

regex = re.compile(r"\b(\w+)=([^=]*)(?=\s\w+=\s*|$)")
diction = dict(regex.findall(value))

The result is {'ActionSuccess': 'True;', 'AdditionalActionsBitMask': '0}'}

To convert a Python string to JSON, use the json. loads() function. The loads() method accepts a valid json string and returns a dictionary to access all elements.

I would turn your string into valid JSON following way:

import json
import re
value= "{ActionSuccess=True; AdditionalActionsBitMask=0},{ActionSuccess=True; AdditionalActionsBitMask=0}"
valuejson = '[' + re.sub(r'\b','"',value).replace(';',',').replace('=',':') + ']'
data = json.loads(valuejson)
print(data)

output

[{'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'}, {'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'}]

I place " where word boundary are (note that \b is zero-length so nothing will be removed) then change ; to , and = to : , finally encose whole string into [ and ] to get list of dict s. Beware that this solution is made specifically to your shown example, so please test it carefully for your other use cases.

If you have access to documentation of what is giving you said response please consult it regarding what format is used in response. If it is not proprietary one you might be able to find converter for it on PyPI .

Because you input the wrong JSON string, {'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'} and {'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'} should have key for them, try this:

import json
data = '{\"block1\":{\"ActionSuccess\":\"True\", \"AdditionalActionsBitMask\":\"0\"},\"block2\":{\"ActionSuccess\":\"True\", \"AdditionalActionsBitMask\":\"0\"}}'
print(json.loads(data))

output:

{'block1': {'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'}, 'block2': {'ActionSuccess': 'True', 'AdditionalActionsBitMask': '0'}}

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