将列表转换为JSON对象

9

我有一个巨大的文本文件。

line 1
line 2
line 3
...

我已将其转换为一个列表的数组:
[['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10'], ...]

我想将这个列表转换为JSON对象,就像这样:
[{'title1': 'String 1', 'title2': 'String 2', ... , 'title7': 'String 7'},
 {'title1': 'String 8', ..., 'title7': 'String 14'}, ...]

我不确定该怎么做。需要帮忙吗?


5
不,它不是它的副本。 - Haseeb Ahmad
5个回答

17

补充alexce的回答,你可以很容易地将重构的数据转换成JSON:

import json
json.dumps(result)

顶级数组存在潜在的安全问题。我不确定它们在现代浏览器中是否仍然有效,但您可能需要考虑将其封装在对象中。

import json
json.dumps({'results': result})

4
为了解决这个问题,你需要将输入列表按照每7个一组进行分割。我们可以使用这种方法来实现。然后,使用列表推导式生成一个字典列表:
>>> from pprint import pprint
>>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
... ['String 11']]
>>> def chunks(l, n):
...     """Yield successive n-sized chunks from l."""
...     for i in range(0, len(l), n):
...         yield l[i:i+n]
... 
>>>
>>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))} 
              for chunk in chunks(l, 7)]
>>> pprint(result)
[{'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 10',
  'title4': 'String 11'}]

如果我想要多个标题(例如,“title”,“convert”,“json”等),而不是使用title1,title2等递增的方式。 - Haseeb Ahmad
1
@ahmadhas 好的,抱歉,回答被问出来的问题。 - alecxe

1
正如 @alecxe 指出的那样,您需要将从文件中获得的列表数组分成具有 7 个或更少元素值的组。然后,您可以取任何 7 个标题的列表,并将它们用作键来创建最终列表中每个 json 对象的字典。
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)

输出:

[{'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'}]

0
ll = [['String 1'],['String 2']]

# 1- Unlist
ll = sum(ll, [])
# 2- Make list to json
list_with_dics = [{"title"+str(i+1): val} for i, val in enumerate(ll)]

结果:[{'标题1':'字符串1'},{'标题2':'字符串2'}]

0

在序列化之前将一个类定义为自定义类型。然后在主类中设置它并在循环中返回,使用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)

在主类中:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接