【问题标题】:Convert a list to json objects将列表转换为 json 对象
【发布时间】:2016-10-06 07:45:09
【问题描述】:

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

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

我不知道该怎么做。有什么帮助吗?

【问题讨论】:

标签: python arrays json


【解决方案1】:

要解决这个问题,您需要将输入列表拆分为块,在您的情况下为 7。为此,让我们使用this approach。然后,使用 list comprehension 生成字典列表:

>>> 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、ttitle2、... incumnting。
  • @ahmadhas 好吧,对不起,回答了被问到的问题。
【解决方案2】:

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

import json
json.dumps(result)

顶级数组有一些潜在的security concerns。我不确定它们在现代浏览器中是否仍然有效,但您可能需要考虑将其包装在一个对象中。

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

【讨论】:

    【解决方案3】:

    正如@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'}]
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-01
        • 1970-01-01
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多