Home > database >  How can I convert a string response to a valid JSON?
How can I convert a string response to a valid JSON?

Time:12-15

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}'}

CodePudding user response:

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 dicts. 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.

CodePudding user response:

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'}}
  • Related