Convert a list to json objects

后端 未结 4 1661
我寻月下人不归
我寻月下人不归 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:10

    As @alecxe pointed out, you need to divide the array of lists you got from the file into groups of values with 7 or fewer elements. You can then take a list of any 7 titles you want and use them as keys to create the dictionary of each json object in the final list.

    try:
        from itertools import izip
    except ImportError:  # Python 3
        izip = zip
    
    try:
        xrange
    except NameError:  # Python 3
        xrange = range
    
    def grouper(n, sequence):
        for i in xrange(0, len(sequence), n):
            yield sequence[i:i+n]
    
    data = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
            ['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
            ['String 10']]
    
    titles = ['title1', 'title2', 'title3', 'title4', 'title5', 'title6', 'title7']
    
    values = [e[0] for g in grouper(7, data) for e in g]
    keys = (titles[i%7] for i in xrange(len(values)))
    
    objs = [dict(g) for g in grouper(7, list(izip(keys, values)))]
    print(objs)
    

    Output:

    [{'title1': 'String 1', 'title2': 'String 2', 'title3': 'String 3',
      'title4': 'String 4', 'title5': 'String 5', 'title6': 'String 6',
      'title7': 'String 7'}, {'title1': 'String 8', 'title2': 'String 9',
      'title3': 'String 9', 'title4': 'String 10'}]
    

提交回复
热议问题