简体   繁体   中英

Convert string (without quotation marks) to JSON in Python

I know that there is a method json.loads(string) but it will work only if I got String formatted to the JSON style. The String I have is in this form:

{
data1: {
    x1: 'xyz'
},
data2 {
    y1: 'datadata'
 },
identify: {
    title: {
       text: 'Some important things'
     }
    }
}

Is there any trick to do that?

I cannot stress enough how clunky I think this solution is, but it does the job. First, I'm assuming the OP made a typo and meant "data2**:**" or this solution will need to be even more complex.

First, create a function that includes the much needed quotation marks.

def fix_element(elem):
if elem[-1] == ':':
    return '"{}":'.format(elem[:-1])
else:
    return elem

Second, parse the text of your object, using only double quotes:

    text = """{
data1: {
    x1: 'xyz'
},
data2: {
    y1: 'datadata'
 },
identify: {
    title: {
       text: 'Some important things'
     }
    }
}""".replace("\'", '"')enter code here

Then correct all elements of the text:

fixed_elem = [fix_element(elem) for elem in text.split()]
fixed_text = ''.join(fixed_elem)

Possibly a solution based on regular expressions would work more succinctly, but I don't have the time or desire to find the correct expressions, to be honest.

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