0

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?

13
  • 1
    What you've got is not JSON. It's not even nearly JSON. So the json library is not going to help you. If it's some other kind of standard format, you might be able to find a tool, otherwise I think you're going to have to write something custom for yourself. Commented Oct 27, 2017 at 13:33
  • @khelwood I know it is not JSON becouse it has no quotes, you don't need to tell me that. That's why I asked the question! Commented Oct 27, 2017 at 13:34
  • 2
    I'm confused. Do you want to convert TO or FROM json? Your title says "to" but you said you tried loads, which converts from json. Commented Oct 27, 2017 at 13:36
  • Your input data has a function declaration inside. How would you encode a function to JSON? Commented Oct 27, 2017 at 13:36
  • 1
    Add the quotes by parsing the whole text, then... You can use regular expressions or you can just find the ':' in your text and add the quotes to them! Commented Oct 30, 2017 at 11:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.