Convert following data to JSON format in python
Question: I have a file with following content which is generated by some other program.
Please note that each one has a new line character at the end.

    
    
    {'a':1,'b':534}
    {'a':4,'b':882}
    {'a':2,'b':964}
    .
    .
    so on...
    

How do I convert this into valid JSON format?

The above should be printed something like this

    
    
    {
        "Sale": [
            {
                "a": 1,
                "b": 534
            },
            {
                "a": 4,
                "b": 882
            },
            {
                "a": 2,
                "b": 964
            }
        ]
    }
    

I can do it in JQuery but I need to do this in python as i am not good at
python but i need to make it runnable through bash script hence the need to
make it to a python script.

I am gonna share the jquery solution just in case you need to refer.

    
    
    result = replaceAll(result,"'","\"");
    result = replaceAll(result,"}, {",",");
    result = replaceAll(result,"}{","},{"); 
    result = replaceAll(result,"}\n{","},{");
    result = "{\"Sale\":["+result+"]}";
    //alert(result);
    

replaceAll function is

    
    
    function replaceAll(str, find, replace) {
     var i = str.indexOf(find);
     if (i > -1){
       str = str.replace(find, replace); 
       i = i + replace.length;
       var st2 = str.substring(i);
       if(st2.indexOf(find) > -1){
         str = str.substring(0,i) + replaceAll(st2, find, replace);
       }       
     }
     return str;
    }
    

The above works but i need a python alternative to this.


Answer: 
    from ast import literal_eval
    with open('data.txt') as f:
        sale = [literal_eval(line) for line in f]
        data = {'Sale': sale}
        print(data)
    

Output

    
    
    {'Sale': [{'a': 1, 'b': 534}, {'a': 4, 'b': 882}, {'a': 2, 'b': 964}]}
    

From there, you can use the [`json`
library](https://docs.python.org/2/library/json.html) to write this to file in
JSON format.

    
    
    import json
    json.dumps(data, indent=4)
    

