Home > database >  How to convert unquoted list of dictionaries to proper json format
How to convert unquoted list of dictionaries to proper json format

Time:04-07

I have a list of dictionaries that are coming out unquoted, such as below:

'[{reason: NA, employeeName: bob smith}, {reason: NA, employeName: tom jones}]'

I need to have this converted to a proper json format to look like this:

[{"reason": "NA", "employeeName:" "bob smith"}, {"reason": "NA", "employeName": "tom jones"}]

How can I accomplish this?

CodePudding user response:

result=[]
for i in list_dict:
   s=str(i)
   d = dict([
    (x.split(':')[0].strip(), x.split(':')[1].strip("' "))
    for x in s.strip("{}").split(',')
   ])
   result.append(d)

CodePudding user response:

You should use regexp for that. There you go :

import json
import re

l = '[{reason: NA, employeeName: bob smith}, {reason: NA, employeName: tom jones}]'
res = []
objects = re.findall(r'{[^}]*}', l)
for o in objects:
    attr = re.findall(r'([\w ]*):([\w ]*)', o)
    res.append({}) 
    for a in attr:
        res[-1][a[0].strip()] = a[1].strip()
print(json.dumps(res))

CodePudding user response:

Here is my small Python Example with the json lib.

import json

data=[{"reason": "NA", "employeeName:" "bob smith"}, {"reason": "NA", "employeName": "tom jones"}]

json.dumps(data)
# output:
#'[{"reason": "NA", "employeeName:": "bob smith"}, {"reason": "NA", "employeName": "tom jones"}]'
  • Related