使用Python在JSON对象中搜索查询的最佳方法
使用Python在JSON对象中搜索查询的最佳方法,python,json,search,Python,Json,Search,我需要创建一个适当的文件存储系统,这是高效率的。我一直在使用Python解决这个问题,并试图通过将类似JSON的字符串作为字典来解析它。我不确定自己做错了什么,因为似乎有更好的方法。我只是想试着了解是否有更好的方法,如果有,我该怎么做? 存储了大约5000-10000个不同的JSON对象,并触发了1000多个查询以获取或删除存储中的内容 这是我的方法 import json import sys store = [] def getData(target): for data in s
我需要创建一个适当的文件存储系统,这是高效率的。我一直在使用Python解决这个问题,并试图通过将类似JSON的字符串作为字典来解析它。我不确定自己做错了什么,因为似乎有更好的方法。我只是想试着了解是否有更好的方法,如果有,我该怎么做? 存储了大约5000-10000个不同的JSON对象,并触发了1000多个查询以获取或删除存储中的内容 这是我的方法
import json
import sys
store = []
def getData(target):
for data in store:
flag=True
for k,v in target.items():
if isinstance(v,dict):
return getData(v)
continue
elif isinstance(v, list):
for i in v:
if i not in data["list"]:
flag = False
continue
elif data.get(k) != v:
flag = False
continue
if flag:
print(json.dumps(data,separators=(',', ':')))
return True
def deleteData(value):
for data in store:
flag = True
for k, v in value.items():
if isinstance(v, dict):
for i_k, i_v in v.items():
if data[k].get(i_k) != i_v:
flag = False
continue
elif isinstance(v, list):
for i in v:
if i not in data["list"]:
flag = False
continue
elif data.get(k) != v:
flag = False
continue
if flag and data in store:
store.remove(data)
def parseInput():
for command in sys.stdin:
if not command:
return
operation, value = command.split(" ",maxsplit=1)
objects = json.loads(value)
if operation == 'add':
store.append(objects)
elif operation == 'get':
getData(objects)
elif operation == 'delete':
deleteData(objects)
else:
return
parseInput()
输入:
add {"id":1,"last":"Doe","first":"John","location":{"city":"Oakland","state":"CA","postalCode":"94607"},"active":true}
add {"id":2,"last":"Doe","first":"Jane","location":{"city":"San Francisco","state":"CA","postalCode":"94105"},"active":true}
add {"id":3,"last":"Black","first":"Jim","location":{"city":"Spokane","state":"WA","postalCode":"99207"},"active":true}
add {"id":4,"last":"Frost","first":"Jack","location":{"city":"Seattle","state":"WA","postalCode":"98204"},"active":false}
get {"location":{"state":"WA"},"active":true}
get {"id":1}
get {"active":true}
delete {"active":true}
get {}
输出:
{"id":3,"last":"Black","first":"Jim","location":{"city":"Spokane","state":"WA","postalCode":"99207"},"active":true}
{"id":1,"last":"Doe","first":"John","location":{"city":"Oakland","state":"CA","postalCode":"94607"},"active":true}
谢谢你的帮助 请不要在api或网站的概念中使用递归。只需通过加载字符串来存储json对象。起初我没有,但要遍历嵌套字典,我想我必须使用它。我不明白你的意思。加载字符串?我正在这么做,对吗?对于GET,我必须使用对象。您使用递归的目的是什么?查看嵌套字典。可以遍历“n”个嵌套字典,所以要在其中搜索,我使用递归@NanthakumarJJ