How do I convert this string to a dictionary
I'm trying regex r"},\s\]"
, but didn't get the desired result.
HTTP request body values
var sample = {
"date": "2022. 03. 23. 16:18",
"list":
[
{
"name": "USD",
"var1":"1236.26",
"var2":"1193.74",
"var3":"1226.90",
"var4":"1203.10",
"var5":"1215.00"
},
{
"name": "JPY",
"var1":"1020.81",
"var2":"985.71",
"var3":"1013.09",
"var4":"993.43",
"var5":"1003.26"
},
]
}
CodePudding user response:
First we need to get rid of any trailing commas:
_sample = sample.replace("\n", "").replace(" ", "").replace(",]", "]")
You can also use regex for this:
import re
_sample = re.sub(r",(\s) ]", "]", sample)
Then use json.loads()
to parse it into a dict.
import json
outcome = json.loads(_sample)
CodePudding user response:
import json
sample = """{
"date": "2022. 03. 23. 16:18",
"list":
[
{
"name": "USD",
"var1": "1236.26",
"var2": "1193.74",
"var3": "1226.90",
"var4": "1203.10",
"var5": "1215.00"
},
{
"name": "JPY",
"var1": "1020.81",
"var2": "985.71",
"var3": "1013.09",
"var4": "993.43",
"var5": "1003.26"
},
]
}"""
to_dict = json.loads(sample)