Python 将列表转换为 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37661863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:45:43  来源:igfitidea点击:

Convert a list to json objects

pythonarraysjson

提问by ahmadhas

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'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10'], ...]

I want to convert this list to JSON objects, like this:

我想将此列表转换为 JSON 对象,如下所示:

[{'title1': 'String 1', 'title2': 'String 2', ... , 'title7': 'String 7'},
 {'title1': 'String 8', ..., 'title7': 'String 14'}, ...]

I am not sure how to do it. Any help.?

我不知道该怎么做。任何帮助。?

回答by ngraves

Just adding onto alexce's response, you can easily convert the restructured data into JSON:

只需添加到 alexce 的响应中,您就可以轻松地将重组后的数据转换为 JSON:

import json
json.dumps(result)

There are some potential security concernswith top-level arrays. I'm not sure if they're still valid with modern browsers, but you may want to consider wrapping it in an object.

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

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

回答by alecxe

To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehensionproducing a list of dictionaries:

要解决此问题,您需要将输入列表拆分为 chunks,在您的情况下为 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'}]

回答by martineau

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.

正如@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)

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

回答by bazo

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

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