skip to Main Content

My AI model generates this string:

'{"name": "hammer 1.5"", "brand": "Eurosteel"}' 

I want to turn it into dict using json.loads. But it is not possible because of "hammer 1.5"" in value of name key. So I want to turn my string into this string:

'{'name': 'hammer 1.5"', 'brand': 'Eurosteel'}' 

How could I do that? I want to do it with function to be able to apply it to all similar cases.

P.S.
Another option is to add before ":

'{"name": "hammer 1.5"", "brand": "Eurosteel"}' 

2

Answers


  1. "… I want to turn it into dict …

    … I want to do it with function to be able to apply it to all similar cases. …"

    Use a regular expression to capture the values.

    As a note, if the value contains a ", or "}, this pattern will fail.

    "(.+?)": "(.+?)"[,}]
    

    Here is an example

    import re
    s = '{"name": "hammer 1.5"", "brand": "Eurosteel"}'
    d = dict(re.findall('"(.+?)": "(.+?)"[,}]', s))
    

    Output

    {'name': 'hammer 1.5"', 'brand': 'Eurosteel'}
    
    Login or Signup to reply.
  2. You could use json.dumps to make the conversion of the data into a dictionary and apply the correct quotes around keys and values:

    import json
    data = '{"name": "hammer 1.5", "brand": "Eurosteel"}'
    dct = json.loads(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search