1

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.

10
  • 4
    What have you tried so far? SO is not a code factory. If you want our help you have to show some effort. Commented Nov 1, 2013 at 11:02
  • So far, pattern substitution but it's kind of a hack, I'm sure there is a better way to do it. Commented Nov 1, 2013 at 11:06
  • "I will need to decode the Python back into the original string format" -- in this case, you probably want to write a custom json encode/decoder Commented Nov 1, 2013 at 11:07
  • 4
    This looks sufficiently different from JSON that you won't have much success with any JSON parser, custom or not. In particular, {0,0,32,22} appears to be intended as an array, but it starts with the same delimiter as a dictionary and the only way to distinguish it from a dictionary is to look ahead (indefinitely) and see that there's no = value part (this is in start contrast to JSON, where you can distinguish arrays and dicts by their starting delimiter). Where is this stupid data format from? Commented Nov 1, 2013 at 11:08
  • 1
    It is ugly but seems to work import json; import re; v1 = re.sub(r'([a-zA-Z]+)', r'"\g<1>"', v.replace('=', ':').replace("\n", "")); json.loads(re.sub(r"{([^:]+)}", "[\g<1>]", v1)); Commented Nov 1, 2013 at 11:27

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! I have still kept my automaton because the value could also have some " like "here is my text" so I ended-up with some issues with the regexp. Thanks again for having taken time to provide a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.