如何使用同一对象内的另一个项目引用json对象中的项目

时间:2019-04-30 20:07:21

标签: python json

我有一个包含许多项目的JSON对象,并且希望能够使用该对象内部的值之一来取回该对象中的其他项目。

我想用“ Abbv”搜索JSON对象,然后取回“设置”

[
    {"Abbv": "VIS", "Set": "Visions"},
    {"Abbv": "5ED", "Set": "Fifth Edition"},
    {"Abbv": "POR", "Set": "Portal"},
    {"Abbv": "WTL", "Set": "Weatherlight"}
]

4 个答案:

答案 0 :(得分:0)

var today = new Date();
var MonitorStartTime = new Date();
var MonitorStopTime = new Date();
MonitorStartTime.setHours(20, 0); // populate it from 20:00
MonitorStopTime.setHours(6, 0);   // populate it from 06:00
return MonitorStartTime <= MonitorStopTime
     ? (today >= MonitorStartTime && today < MonitorStopTime)
     : (today >= MonitorStartTime || today < MonitorStopTime);

我想这是您想要的结果。您只需指定要搜索的对查找,然后尝试在JSON对象列表中找到它。找到它后,访问该对象的json_objects = [ {"Abbv": "VIS", "Set": "Visions"}, {"Abbv": "5ED", "Set": "Fifth Edition"}, {"Abbv": "POR", "Set": "Portal"}, {"Abbv": "WTL", "Set": "Weatherlight"} ] lookup = ('Abbv', 'POR') for obj in json_objects: if lookup in obj.items(): print(obj['Set']) # 'Portal' 键。

答案 1 :(得分:0)

你的意思是这样吗?

objects = [
    {"Abbv": "VIS", "Set": "Visions"},
    {"Abbv": "5ED", "Set": "Fifth Edition"},
    {"Abbv": "POR", "Set": "Portal"},
    {"Abbv": "WTL", "Set": "Weatherlight"}
]

for obj in objects:
    if obj['Abbv'] == 'VIS':
        print(obj['Set'])

答案 2 :(得分:0)

没有超短解决方案。您将不得不遍历整个列表,尽管如果发现所需的内容也可能会短路。

您可以使用以下功能来做到这一点:

l = [
    {"Abbv": "VIS", "Set": "Visions"},
    {"Abbv": "5ED", "Set": "Fifth Edition"},
    {"Abbv": "POR", "Set": "Portal"},
    {"Abbv": "WTL", "Set": "Weatherlight"}
]
def search_for_abbv(abbv, l):
    """
    l: A list of dicts we want to search through.
    abbv: The abbreviation we want to find
    Returns None if nothing found else the abbreviation.
    """
    for item in l:
        if abbv == item['Abbv']:
            return item['Set']
temp = search_for_abbv('POR', l)
print(temp)

输出:

Portal

请注意,如果您这样做是为了节省内存,那么我可能会使用tuplesnamedtuples的列表。

答案 3 :(得分:0)

如果您只获取少量值,那么最好的选择就是wencakisa的答案。但是,如果要处理更多数据,您可以考虑使用熊猫。在这种情况下,您可以这样获得想要的值:

import pandas as pd

l = [
    {"Abbv": "VIS", "Set": "Visions"},
    {"Abbv": "5ED", "Set": "Fifth Edition"},
    {"Abbv": "POR", "Set": "Portal"},
    {"Abbv": "WTL", "Set": "Weatherlight"}
]
df = pd.DataFrame(l)
val = df.loc[df['Abbv'] == 'POR', 'Set']
print(val)