Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fix JSON Key Values without double-quotes?

Tags:

python

json

regex

I currently have JSON in the below format. Some of the Key values are NOT properly formatted as they are missing double quotes (")

How do I fix these key values to have double-quotes on them?

    {      
Name: "test",
Address: "xyz",
"Age": 40,
"Info": "test"
}

Required:

    {      
"Name": "test",
"Address": "xyz",
"Age": 40,
"Info": "test"
}

Using the below post, I was able to find such key values in the above INVALID JSON. However, I could NOT find an efficient way to replace these found values with double-quotes.

s = "Example: String"
out = re.findall(r'\w+:', s)

How to Escape Double Quote inside JSON

like image 797
mssqlsense Avatar asked Jun 20 '18 12:06

mssqlsense


3 Answers

Using Regex:

import re
data = """{ Name: "test", Address: "xyz"}"""
print( re.sub("(\w+):", r'"\1":',  data) )

Output:

{ "Name": "test", "Address": "xyz"}
like image 50
Rakesh Avatar answered Sep 28 '22 18:09

Rakesh


I had few more issues that I faced in my JSON. Thought of sharing the final solution that worked for me.

jsonStr = re.sub("((?=\D)\w+):", r'"\1":',  jsonStr)
jsonStr = re.sub(": ((?=\D)\w+)", r':"\1"',  jsonStr)
  1. First Line will fix this double-quotes issue for the Key. i.e. Name: "test"
  2. Second Line will fix double-quotes issue for the value. i.e. "Info": test

Also, above will exclude double-quoting within date timestamp which have : (colon) in them.

like image 25
mssqlsense Avatar answered Sep 28 '22 18:09

mssqlsense


You can use online formatter. I know most of them are throwing error for not having double quotes but below one seems handling it nicely!

JSON Formatter

like image 43
Jay Shukla Avatar answered Sep 28 '22 18:09

Jay Shukla