pythonjsonstreamformattingslurp

how to make my json formatted using python


i have json that looks like this:

{
    "message": ".replace(commentRegExp, '')",
    "report_id": 1961272
}{
    "message": ".replace(currDirRegExp, '')",
    "report_id": 1961269
}{
    "message": ".replace(jsSuffixRegExp, '');",
    "report_id": 1961270
}

how to make it into correct format using python i want the json data to look like this:

[
 {
    "message": ".replace(commentRegExp, '')",
    "report_id": 1961272
 },
 {
    "message": ".replace(currDirRegExp, '')",
    "report_id": 1961269
 },
 {
    "message": ".replace(jsSuffixRegExp, '');",
    "report_id": 1961270
 }
]

Solution

  • Something like this will split up the root elements

    import json
    import re
    
    json = '{"message":".replace(commentRegExp, '')","report_id":1961272}{"message":".replace(currDirRegExp, '')","report_id":1961269}{"message":".replace(jsSuffixRegExp, '');","report_id":1961270}'
    
    match_array = re.findall("[{].*?[}]", json)
    
    json_new = ""
    
    for x in match_array:
        json_new+=(x+",")   
    
    json_new = "["+json_new[:-1]+"]"
    

    Edit to Read from file;

    import json
    import re
    
    with open('test.json', 'r') as myfile:
        data=re.sub(r"[\n\t\s]*", "", myfile.read())
    
    match_array = re.findall("[{].*?[}]", data)
    
    json_new = ""
    
    for x in match_array:
        json_new+=(x+",")   
    
    json_new = "["+json_new[:-1]+"]"
    
    print(json_new)
    

    The Bulk of what this solution is doing is based around the [{].*?[}] regex which will find all the json root elements then comma separate them and append square brackets on the start and end