我是JSON的新手, 我想获得标签'来自我的JSON数据 这是我的JSON数据,我使用json.dumps将其转换为JSON格式
a = json.dumps({"Name": "Robert",
"Date" : "January 17th, 2017",
"Address" : "Jakarta"})
我想打印我的JSON数据的标签,有没有可行的方法呢? 我想要的结果是
Name
Date
Address
答案 0 :(得分:2)
您必须将json
转换为dict
,然后labels
与keys
相同。
import json
a = json.dumps({"Name": "Robert",
"Date" : "January 17th, 2017",
"Address" : "Jakarta"})
for key in json.loads(a):
print(key)
输出:
Name
Date
Address
<强>可选强>:
如果您想访问每个项目的值
import json
a = json.dumps({"Name": "Robert",
"Date" : "January 17th, 2017",
"Address" : "Jakarta"})
d = json.loads(a)
for key in d:
print("key: {}, value: {}".format(key, d[key]))
<强> Python2 强>
for key, value in json.loads(a).iteritems():
print("key: {}, value: {}".format(key, value))
<强> Python3 强>
for key, value in json.loads(a).items():
print("key: {}, value: {}".format(key, value))
输出:
key: Name, value: Robert
key: Date, value: January 17th, 2017
key: Address, value: Jakarta
答案 1 :(得分:0)
做出的假设:
您可以按照以下方式执行此操作:
import json
a = json.dumps({"Name": "Robert", "Date" : "January 17th, 2017", "Address" : "Jakarta"})
a_dict = json.loads(a)
for key in a_dict.keys():
print (key)
答案 2 :(得分:0)
我认为你需要使用load来创建一个json对象。所以在Python3中:
import json
a = json.loads('{"Name":"Robert","Date":"January 17th, 2017","Address":"Jakarta"}')
for key, value in a.items() :
print (key)
答案 3 :(得分:0)
下面的python代码将获取json文件作为输入,并在各个级别生成一个带有json标签的文件。
from re import sub
from os.path import abspath, realpath, join, dirname
import json
Srcfilename = input("Enter Srcfilename: ")
file = abspath(Srcfilename)
file_open = open(file, 'r')
file_read = file_open.read()
#print(file_read)
jdata = json.loads(file_read)
def get_keys(dl, keys_list1):
if isinstance(dl, dict):
for key1,info1 in dl.items():
# print(key1)
keys_list1.append(key1)
#print("\nlistinfo:",info1)
if isinstance(info1, dict) or isinstance(info1, list) :
get_keys(info1, keys_list1)
elif isinstance(dl, list):
if isinstance(dl[0], dict):
for key2,info2 in dl[0].items():
# print(key2)
keys_list1.append(key2)
# print("\nlistinfo:",info2)
if isinstance(info2, dict) or isinstance(info2, list) :
get_keys(info2, keys_list1)
keys_list1 = list(dict.fromkeys(keys_list1))
keylist='\n'.join(map(str, keys_list1))
return keylist
keys_list1=[]
Tgtfilename = input("Enter Tgtfilename: ")
new_file = abspath(Tgtfilename)
new_file_open = open(new_file, 'w')
content=get_keys(jdata, keys_list1)
print (keys_list1)
new_file_open.write(content)
new_file_open.close()