这是我的json文件的结构
},
"client1": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"1.1.1.1",
"2.2.2.2",
"3.3.3.3"
]
},
"client2": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"4.4.4.4",
"2.2.2.2"
]
},
我已经看到了导出此json文件特定部分而不是全部内容的方法。基本上,我要做的就是使用用户输入来搜索文件。 我一直在苦苦挣扎的是如何实际使用用户输入来基于输入搜索并打印client1或client2下的所有内容?我确定这只是1或2行代码,但无法弄清楚。 python新手。这是我的代码
data = json.load(open('clients.json'))
def client():
searchq = input('Client to export: '.capitalize())
search = ('""'+searchq+'"')
a = open('Log.json', 'a+')
a.write('Client: \n')
client()
答案 0 :(得分:0)
这应该可以帮助您:
# Safely open the file and load the data into a dictionary
with open('clients.json', 'rt') as dfile:
data = json.load(dfile)
# Ask for the name of the client
query = input('Client to export: ')
# Show the corresponding entry if it exists,
# otherwise show a message
print(data.get(query, 'Not found'))
答案 1 :(得分:0)
首先,我说这是100%的偷偷摸摸的回答,但是您可以做的一件事就是让您的用户使用。 (点)定界格式,用于在字典/ json结构中指定键的“路径”,然后实现一个递归函数来查找该路径下的值,如下所示:
def get(query='', default=None, fragment=None):
"""
Recursive function which returns the value of the terminal
key of the query string supplied, or if no query
is supplied returns the whole fragment (dict).
Query string should take the form: 'each.item.is.a.key', allowing
the user to retrieve the value of a key nested within the fragment to
an arbitrary depth.
:param query: String representation of the path to the key for which
the value should be retrieved
:param default: If default is specified, returns instead of None if query is invalid
:param fragment: The dictionary to inspect
:return: value of the specified key or fragment if no query is supplied
"""
if not query:
return fragment
query = query.split('.')
try:
key = query.pop(0)
try:
if isinstance(fragment, dict) and fragment:
key = int(key) if isinstance(fragment.keys()[0], int) else key
else:
key = int(key)
except ValueError:
pass
fragment = fragment[key]
query = '.'.join(query)
except (IndexError, KeyError) as e:
return default if default is not None else None
if not fragment:
return fragment
return get(query=query, default=default, fragment=fragment)
将会有一百万人来这里提出比这更好的建议,并且毫无疑问也要对该功能进行很多改进,但是由于我已经把它放在身边,所以我以为我会把它放在这里,至少是您的起点。
注意: 片段可能应该作为位置参数或其他东西。 IDK。这不是因为我不得不删除一些特定于应用程序的上下文(它曾经有一个明智的默认状态),而且我不想开始重写内容,所以我留给您自己。
给定一些数据,您可以使用此功能进行一些有趣的事情:
d = {
'woofage': 1,
'woofalot': 2,
'wooftastic': ('woof1', 'woof2', 'woof3'),
'woofgeddon': {
'woofvengers': 'infinity woof'
}
}
尝试以下方法:
get(fragment=d, query='woofage')
get(fragment=d, query='wooftastic')
get(fragment=d, query='wooftastic.0')
get(fragment=d, query='woofgeddon.woofvengers')
get(fragment=d, query='woofalistic', default='ultraWOOF')
一路顺风!
答案 2 :(得分:0)
将json格式传递给Dict,然后查看所需主题并读取或写入
import json
r = {'is_claimed': True, 'rating': 3.5}
r = json.dumps(r) # Here you have json format {"is_claimed": true, "rating": 3.5}
Json的字典:
loaded_r = json.loads(r) # {'is_claimed': True, 'rating': 3.5}
print (r)#Print json format
print (loaded_r) #Print dict
阅读主题
Data=loaded_r['is_claimed'] #Print Topic desired
print(Data) #True
覆盖主题
loaded_r['is_claimed']=False
这也将做同样的事情
print(loaded_r['client1']['description'])