繁体   English   中英

如何选择具有特定值的特定JSON对象?

[英]How to select particular JSON object with specific value?

我里面有多个字典的列表(作为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}]

我想获取作者是保罗的完整对象。 这是我到目前为止编写的代码。

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

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

情况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'

情况二
重复访问

在这种情况下,明智的做法是使用作者名来访问对象要快得多(想想字典!),从而以这种方式重塑数据。

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

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, [...]))

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

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'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM