-1

I have to parse a JSON structure that contains another JSON struct embedded in it. What is the cleanest way to convert the quotes? I came up with this way but wanted to know if there is some ready made way to do it.

def clean():
   kk = """{'id': 'pq-123', 'content': "{'a': 'xyz-123'}", 'img': 'flash.jpg'}"""
   st = kk.find('"')
   end = 1 + st + kk[st+1:].find('"')
   x = kk[0:st].replace("'", '"') + kk[st] + kk[st+1:end+1] + kk[end+1:].replace("'", '"')
   return x
user2399453
  • 2,930
  • 5
  • 33
  • 60
  • 1
    Where is the `kk` from? – Itachi Feb 28 '20 at 06:05
  • Might not work perfectly but looks like using `eval()` might work nicely. Call `eval()` on kk, then `kk['content'] = eval(k['content'])`. Then you can use the builtin `json.dump()` or `json.dumps()` to convert it to JSON. – kimbo Feb 28 '20 at 06:17
  • @kimbo Yes, `evil` can work. It shouldn't be allowed to. There is very, _very_ few occasions where `evil` is warranted; this is not one of them. :) – Amadan Feb 28 '20 at 06:21
  • Are you sure you’re not looking at a Python dict to begin with, perhaps already decoded from a JSON response? – deceze Feb 28 '20 at 06:22
  • @Adaman I've never used `ast.literal_eval` but it looks much safer. Thanks for the info! (For others, see this question for more details https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) – kimbo Feb 28 '20 at 06:28

1 Answers1

2

That is not JSON (as you likely know, which is probably the reason why you want to do the transformation you are asking for). But it is a valid Python literal, that can be parsed by ast.literal_eval:

import ast
import json

data = ast.literal_eval(kk)
valid_json = json.dumps(data)
Amadan
  • 191,408
  • 23
  • 240
  • 301