【问题标题】:How to select particular JSON object with specific value?如何选择具有特定值的特定 JSON 对象?
【发布时间】:2018-05-07 01:30:13
【问题描述】:

我有多个字典列表(作为 JSON )。我有一个值列表,并且基于该值,我希望该 JSON 对象具有该特定值。例如。

[{'content_type': 'Press Release',
  'content_id': '1',
   'Author':John},
{'content_type': 'editorial',
  'content_id': '2',
   'Author': Harry
},
{'content_type': 'Article',
  'content_id': '3',
   'Author':Paul}]

我想获取作者是 Paul 的完整对象。 这是我到目前为止所做的代码。

import json
newJson = "testJsonNewInput.json"
ListForNewJson = []
def testComparision(newJson,oldJson):
   with open(newJson, mode = 'r') as fp_n:
    json_data_new = json.load(fp_n) 
for jData_new in json_data_new:
    ListForNewJson.append(jData_new['author'])

如果需要任何其他信息,请询问。

【问题讨论】:

标签: python json


【解决方案1】:

案例 1
一次性访问

完全可以读取数据并对其进行迭代,返回找到的第一个匹配项。

def access(f, author):
    with open(file) as f:
        data = json.load(f)

    for d in data:
        if d['Author'] == author:
            return d
    else:
        return 'Not Found'

案例 2
重复访问

在这种情况下,明智的做法是重塑您的数据,以便通过作者姓名访问对象更快(想想字典!)。

例如,一种可能的选择是:

with open(file) as f:
    data = json.load(f)

newData = {}
for d in data:
    newData[d['Author']] = d

现在,定义一个函数并将您的预加载数据与作者姓名列表一起传递。

def access(myData, author_list):
    for a in author_list:
        yield myData.get(a)

函数是这样调用的:

for i in access(newData, ['Paul', 'John', ...]):
    print(i)

或者,将结果存储在列表r 中。 list(...) 是必需的,因为 yield 返回一个生成器对象,您必须通过迭代来耗尽它。

r = list(access(newData, [...]))

【讨论】:

    【解决方案2】:

    为什么不做这样的事情呢?它应该很快,您不必加载不会被搜索的作者。

    alreadyknown = {}
    list_of_obj = [{'content_type': 'Press Release',
        'content_id': '1',
        'Author':'John'},
        {'content_type': 'editorial',
        'content_id': '2',
        'Author': 'Harry'
        },
        {'content_type': 'Article',
        'content_id': '3',
        'Author':'Paul'}]
    def func(author):
        if author not in alreadyknown:
            obj = get_obj(author)
            alreadyknown[author] = obj
        return alreadyknown[author]
    def get_obj(auth):
        return [obj for obj in list_of_obj if obj['Author'] is auth]
    print(func('Paul'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2011-03-06
      • 2015-10-27
      • 2019-06-05
      相关资源
      最近更新 更多