Domanda

I have a string that looks like JSON but it's not. I want to convert it into a Python object (back and forth).

Here is the format:

v = "{ TestKey = true,
Calibration = 0,
Blacks = 0,
Brightness = 50,
BasicSetting = { 0,
0,
32,
22},
Whites = 0 }"

I can not use directly json.load(v) on such string. What's the best / easiest way to convert it into a Python object ? Writing a custom Python JSON encoder / decoder ? I will need to decode the Python back into the original string format.

So far, I'm replacing = by : but I face some issues to correctly put the ' in the original string and I don't think it's the best way to do. Any other suggestions ?

Thanks.

È stato utile?

Soluzione

It is ugly as hell and some regex ninja would be able to achieve this using half of the symbols but seems to work:

import json
import re

def parse(v):
    # Remove newlines and replace "=" with ":"
    v1 =  v.replace('=', ':').replace("\n", "")
    # Enclose strings in double quotes
    v2 = re.sub(r'(\d*[a-zA-Z][a-zA-Z0-9]*)', r'"\g<1>"', v1)
    # If you want booleans
    v3 = re.sub(r'"(true|false)"', r'\g<1>', v2)
    # Create lists
    return json.loads(re.sub(r"{([^:]+)}", r'[\g<1>]', v3))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top