以下是我正在加载的JSON数据格式的两个示例:
"address": {
"locality": "London",
"postal_code": "L1 1RE",
"region": "London",
"address_line_1": "1 Tower Road"
},
"date_of_creation": "2013-01-02",
....
"address": {
"postal_code": "KY7 6SD",
"address_line_2": "A Business Park",
"address_line_1": "Headquarters",
"locality": "Fife",
"region": "Glenrothes"
},
"date_of_creation": "2010-02-01",
我想返回一个字符串,该字符串以特定的顺序连接地址对象,该顺序不符合JSON数据的顺序。即
str = address['address_line_1'] + ',' + address['address_line_2'] + ','
+ address['locality'] + ',' + address['region'] + ',' +
address['postal_code']
然而,并不是每个地址对象都包含它们所有的键,顺序并不总是相同的,在第一个例子中,如果值相同(位置和区域(,我不想连接它们。
创建这个字符串的最佳方法是什么?
让我们一步一步地解决这个问题。
问题1:并非所有地址都有所有密钥。
解决方案:如果键存在,则创建一个函数以返回值,否则为空字符串
def get_value(key, json_obj):
if key in json_obj.keys(): # Check if key exists
return json_obj[key] # if yes will return value
return "" # Otherwise empty str
问题2:你不想得到相同的值被计数两次:解决方案
list_of_attributes_to_find = ['address_line_1', 'address_line_2', 'locality', 'region','postal_code' ] # All the values which you want to exclude
def Create_str(address):
list_of_values = [] #For each address
for key in list_of_attributes_to_find: # for each key
if get_value(key, address) and get_value(key, address) not in list_of_values:
list_of_values.append(get_value(key, address)) # Check if the value is not empty and value is not already in the output list_of_values
return ",".join(list_of_values) # Return the output with formatted output
address = {
"postal_code": "KY7 6SD",
"address_line_2": "A Business Park",
"address_line_1": "Headquarters",
"locality": "Fife",
"region": "Glenrothes"
}
输出:
Headquarters,A Business Park,Fife,Glenrothes,KY7 6SD