Convert a list to json objects

后端 未结 4 1656
我寻月下人不归
我寻月下人不归 2020-12-17 03:46

I have a huge text file.

line 1
line 2
line 3
...

I have converted it into an array of lists:

[[\'String 1\'],[\'String 2\'         


        
4条回答
  •  遥遥无期
    2020-12-17 04:17

    Define a class as custom type before serializing. Then set this in a loop in the main class and return using json.dumps()

    import json
    
    class CustomType:
        def __init__(self, title, text):
            self.title = title
            self.text = text
    
        def toJSON(self):
            '''
            Serialize the object custom object
            '''
            return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
    

    in main class:

    def get_json_data():
        '''
        Convert string array to json array
        '''
        result = []
        for item in data:
            obj = CustomType("title(n)",item)
            result.append(json.loads(obj.toJSON()))
    
        return json.dumps(result)
    

提交回复
热议问题