【发布时间】:2017-11-02 02:55:03
【问题描述】:
我正在尝试编写一个非常简单但模块化的脚本来重命名文件。
我想处理 JSON 文件的内容,但是,我坚持返回一个键(对象?)的所有子值,而不仅仅是一个。
到目前为止,我的测试代码如下所示:
import json
DB_dict = json.load(open("../source_code/db3.json", encoding='utf-8-sig'))
old_names_of_Book1 = DB_dict["Book1"]["Book1_section1"]["old_name"]
print(old_names_of_Book1)
print("________________________")
for key, values in DB_dict.items():
print(key)
print(values)
导入的db3.json的内容:
{
"Book1": {
"Book1_section1": {
"old_name": "Adventures of X1",
"new_name": "Adventures of Y1"
},
"Book1_section2": {
"old_name": "Adventures of X2",
"new_name": "Adventures of Y2"
},
"Book1_section3": {
"old_name": "Adventures of X3",
"new_name": "Adventures of Y3"
},
"Book1_section4": {
"old_name": "Adventures of X4",
"new_name": "Adventures of Y4"
}
},
"Book2": {
"Book2_section1": {
"old_name": "Adventures of X1",
"new_name": "Adventures of Y1"
},
"Book2_section2": {
"old_name": "Adventures of X2",
"new_name": "Adventures of Y2"
},
"Book2_section3": {
"old_name": "Adventures of X3",
"new_name": "Adventures of Y3"
},
"Book2_section4": {
"old_name": "Adventures of X4",
"new_name": "Adventures of Y4"
}
}
}
JSON 文件中的 Book1、Book2、Bookx 键将在脚本中进行硬编码,因为我想使用分支语句根据用户输入重命名不同的文件。例如,如果用户选择 Book1,则将每个 old_name 值重命名为 new_name,但不要介意“部分”的出现次数。
(部分的数量 (Book1_section1) 可能会随着时间的推移而改变,因此,我希望我的脚本在每次出现的部分上进行迭代。)
我的问题是,我不知道如何忽略我的 JSON 中的 Book1_section1、Book1_section2 等...键,只解析它们的内容。与
print(DB_dict["Book1"]["Book1_section1"]["old_name"])
我可以得到我想要的值,但我不知道如何得到所有的值。
【问题讨论】:
-
你试过 your_dict.values() 了吗?
标签: python json python-3.x