我一直试图找到搜索特定值并提取数据的最佳方法。我是新人,希望我的措辞正确。
{"family": {
"name": "Mary",
"age": "32",
"sex": "female",
"kids": [
{
"name": "jim",
"age": "10",
"sex": "male",
"dob_year": "2007",
"ssn": "123-23-1234"
},
{
"name": "jill",
"age": "6",
"sex": "female",
"dob_year": "2011",
"ssn": "123-23-1235"
}]}}
如果我需要搜索包含“1234”的“ssn”并返回“名称”“jim”,那么最好的方法是什么呢?
答案 0 :(得分:0)
您可以先迭代孩子并应用条件
import json
js = '''your json text data'''
j = json.loads(js)
for items in j['family']['kids']:
if '1234' in items['ssn']:
print(items['name'])
输出
'jim'
答案 1 :(得分:0)
使用json包,如下所示
ans = '{"family": {
"name": "Mary",
"age": "32",
"sex": "female",
"kids": [
{
"name": "jim",
"age": "10",
"sex": "male",
"dob_year": "2007",
"ssn": "123-23-1234"
},
{
"name": "jill",
"age": "6",
"sex": "female",
"dob_year": "2011",
"ssn": "123-23-1235"
}]}}'
temp = json.loads(ans)
for kid in temp['family']['kids']:
print kid['name'],kid['ssn']
希望这就是你要找的东西。
答案 2 :(得分:0)
假设您将json文本加载到js变量中。 kn = next((sj['name'] for sj in js['family']['kids'] if ('1234' in sj['ssn'])), None)
kn将为您提供名称,否则将为无。当然,您可以将条件更改为变量。希望它有所帮助。
答案 3 :(得分:0)
我更愿意提供处理这种情况的常用方法,基于python函数编程的直到方法,使用此方法,您可以找到您的目标(提供默认值)如果没有找到),你可以轻松地将你的过滤标准和候选人分开。
json_str = """
{"family": {
"name": "Mary",
"age": "32",
"sex": "female",
"kids": [
{
"name": "jim",
"age": "10",
"sex": "male",
"dob_year": "2007",
"ssn": "123-23-1234"
},
{
"name": "jill",
"age": "6",
"sex": "female",
"dob_year": "2011",
"ssn": "123-23-1235"
}]}}
"""
将数据加载到python dict对象
import json
data = json.loads(json_str)
现在到了这里:
def until(terminate, iterator, default=None):
try:
i = next(iterator)
if terminate(i):
return i
return until(terminate, iterator, default)
except StopIteration:
return default
ssn_target = '1234'
target_kid = until(lambda kid: ssn_target in kid['ssn'], iter(data['family']['kids']))
if target_kid is not None:
print(target_kid['name'])
else:
print('Opps! not found')
请注意:
Python对可以进行多少次递归调用(通常约为1000)有一个相当小的限制,因此可迭代列表不应该太长。
答案 4 :(得分:0)
实际上是关于从文件
中提取的问题所以您在这里
import json
with open('data.json') as json_file:
data = json.load(json_file)
for kid in data['family']['kids']:
if '1234' in kid['ssn']:
print(kid['name'])
其他阅读:https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/