Make python string jsonable by removing inner quotes

Viewed 38

Here are 2 examples of what I'm trying to achieve

bad_str = '{"path": "/sources/", "known_cmd": "set", "other_args": "stocks_news;["newsapi",;"feedparser"]", "input": "set stocks_news ["newsapi", "feedparser"]"}'
good_str = '{"path": "/sources/", "known_cmd": "set", "other_args": "stocks_news;[newsapi,;feedparser]", "input": "set stocks_news [newsapi, feedparser]"}'
bad_str = '{"path":"/stocks/ta/", "known_cmd":"ema", "other_args":"72,89;",";1",";1", "input":"ema 72,89 ","1","1"}'
good_str = '{"path":"/stocks/ta/", "known_cmd":"ema", "other_args":"72,89;,;1,;1", "input":"ema 72,89 ,1,1"}'

The goal here would be removing the quotes inside each "value" in order to make the string a valid json.

Any suggestion? I've been trying with regular expressions and by doing python operations, but with no luck so far.

Here's an example that work for the 1st example above, but doesn't for the 2nd.

test_str = '{"path": "/sources/", "known_cmd": "set", "other_args": "stocks_news;["newsapi",;"feedparser"]", "input": "set stocks_news ["newsapi", "feedparser"]"}'
test_str = test_str.replace('"', '').replace("{", "{\"").replace("}", "\"}").replace(": ", ":").replace(":", "\":\"").replace(", ",",").replace(",","\",\"").replace("{","").replace("}","")
test_str

for index, char in enumerate(test_str):
    if char == ",":
        if not (test_str[index-1] == "\"" and test_str[index+1] == "\""):
            test_str[index] = "."
            print(test_str[index])

fix_list = test_str.split(",")

for index, item in enumerate(fix_list):
    
    if ":" not in fix_list[index] :
        fix_list[index-1] = fix_list[index-1] + "," + fix_list[index]
        del fix_list[index]

for index, item in enumerate(fix_list):
    fix_list[index] = item.lstrip().rstrip()
    
    if item.count("\"") > 4:

        tmp_list = item.split(":")

        tmp_index = tmp_list[0]
        tmp_value = tmp_list[1].replace("\"", "")
        fix_list[index] = tmp_index + ":" + "\"" + tmp_value + "\""

fixed_str = "{" + ",".join(fix_list) + "}"
fixed_str

With output:

'{"path":"/sources/","known_cmd":"set","other_args":"stocks_news;[newsapi,;feedparser]","input":"set stocks_news [newsapi,feedparser]"}'

Thanks in advance!

0 Answers
Related