data = ['reply': '{"osc":{"version":"1.0"}}']
data1 = ['reply':'{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}']
我需要使用python 3.6从data和data1中获取“1.0”值。
我怎样才能做到这一点?
答案 0 :(得分:0)
您的数据和数据1在python中是无效的数据类型,因此我将它们转换为有效的字典。
from operator import getitem
data = {'reply': {"osc":{"version":"1.0"}}}
data1 = {'reply':{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}}
def get_item(keys, dict_):
return reduce(getitem, keys, dict_)
print(get_item(['reply','osc','version'], data))
print(get_item(['reply','device','network', 'ipv4_dante',"auto"],data1))
>>>1.0
1.0
另一种方法,数据和data1为字符串:
class GetValue:
def __init__(self, string):
self.string = string
self.new_keys = {}
def clean_data(self, data):
if data[2] == '{':
get_json_data = len(data) - 3
else:
get_json_data = len(data) - 1
modified_data = [val for val in list(data[data.find(':')+1:get_json_data])
if val is not "'" ]
return json.loads(''.join(modified_data))
def get_recurvise_key(self, data, dict_):
for key, val in dict_.items():
self.new_keys.setdefault(data,[]).append(key)
if isinstance(val, dict):
self.get_recurvise_key(data, val)
return self.new_keys.get(data)
def get_value(self):
get_data = self.clean_data(self.string)
get_keys = self.get_recurvise_key(self.string,get_data)
value = reduce(getitem, get_keys, get_data)
return value
data = """['{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}']"""
data1 = """['reply':'{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}']"""
obj_data = GetValue(data)
obj_data1 = GetValue(data1)
print(obj_data.get_value(), obj_data1.get_value())
>>> 1.0 1.0
答案 1 :(得分:0)
您可以递归地获得该结果,如:
def bottom_value(in_data):
def recurse_to_bottom(a_dict):
if isinstance(a_dict, dict):
a_key = list(a_dict)[0]
return recurse_to_bottom(a_dict[a_key])
return a_dict
return recurse_to_bottom(json.loads(in_data['reply']))
import json
data = {'reply': '{"osc":{"version":"1.0"}}'}
data1 = {'reply':'{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}'}
print(bottom_value(data))
print(bottom_value(data1))
1.0
1.0
答案 2 :(得分:0)
修复数据后:
data1 = {'reply':{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}}
只要它仍然是字典,继续从字典中获取值:
d = data1
while isinstance(d, dict):
d = list(d.values())[0]
print(d)
#1.0
答案 3 :(得分:0)
您可以尝试正则表达式:
import re
pattern=r'(?<=")[0-9.]+'
data1="""['reply': '{"osc":{"version":"1.0"}}']"""
data2="""['reply':'{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}']"""
def find_value(data):
return re.findall(pattern,data)[0]
输出:
print(find_value(data1))
输出:
1.0
第二
print(find_value(data2))
输出
1.0