2

I need to parse json from a partial string I get back from a web service. I have the following snippet of code which is working fine but is extremely ugly. Is there a better or cleaner way to do this?

x = '"1":{"name":"item one","code":"1"},"2":{"name":"item two","code":"2"},"3":{"name":"item three","code":"3"}'
split = x.split('},')
index = 0
for s in split:
    split[index] = '{' + s + '}}'
    index += 1
joined = ','.join(split)
joined = '[' + joined[:-1] + ']'
j = json.loads(joined)
print(j)

Here is the result:

[{'1': {'name': 'item one', 'code': '1'}},
 {'2': {'name': 'item two', 'code': '2'}},
 {'3': {'name': 'item three', 'code': '3'}}]
4
  • 2
    Can't you just do x = json.loads("{" + x + "}") then do whatever you like with it as a dict? Commented Aug 31, 2021 at 0:24
  • @JonSG That won't produce the same expected output. Commented Aug 31, 2021 at 0:47
  • The first thing I would do is find out if the web service can be changed to return real JSON. Commented Aug 31, 2021 at 1:02
  • 1
    @Selcuk Yes, that is not a complete solution, but I see you were able to use it as the core of your solution which was my intention. Commented Aug 31, 2021 at 13:37

2 Answers 2

3

You can use the following snippet:

>>> [dict([t]) for t in json.loads(f"{{{x}}}").items()]
[{'1': {'name': 'item one', 'code': '1'}},
 {'2': {'name': 'item two', 'code': '2'}},
 {'3': {'name': 'item three', 'code': '3'}}]
Sign up to request clarification or add additional context in comments.

Comments

2

You can fix the inconsistency by hand (add the missing braces) and use json module to parse:

data = json.loads('{' + x + '}')

Then you can convert the parsed data to the desired representation:

[{item[0]: item[1]} for item in data.items()]

#[{'1': {'name': 'item one', 'code': '1'}}, 
# {'2': {'name': 'item two', 'code': '2'}}, 
# {'3': {'name': 'item three', 'code': '3'}}]

Otherwise, you will end up implementing your own JSON parser, which is not trivial.

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.