Python 2.7:加载一个 JSON 文件搜索一个值,替换它,并另存为新的 JSON
Python 2.7: Load a JSON file search for a value, replace it, and save as new JSON
如标题中所述,我正在尝试制作一个简单的 py 脚本,可以从终端 运行 执行以下操作:
- 在当前工作目录和嵌套文件夹中查找所有 JSON 文件(这部分工作正常)
- 加载所述文件
- 递归搜索特定值或子字符串
- 如果该值匹配,则将其替换为用户新建立的值
- 完成后,将所有已修改的 json 文件保存到当前目录的 "converted" 文件夹中。
就是说,问题是当我尝试下面发布的递归搜索方法时,因为我对 python 还很陌生,我将不胜感激对这个问题的任何帮助,我想它是.. . 我正在使用的 json 文件或我正在使用的搜索方法。
简化问题,我搜索的值永远不会与 object 中的任何内容匹配,无论是键还是纯粹的字符串值。尝试了多种方法来执行递归搜索,但无法找到匹配项。
例如:考虑到示例 json,我想替换值 "selectable_parts" 或 "static_parts" 甚至更深的结构“1h_mod310_door_00”但是似乎我的搜索方法无法在 "object[object][children][0][children][5][name]" 中达到此值(希望这有帮助)。
示例 JSON:(https://drive.google.com/open?id=0B2-Bn2b0ujjVdW5YVGg3REg3OWs)
"""KEYWORD REPLACING MODULE."""
import os
import json
# functions
def get_files():
"""lists files"""
exclude = set(['.vscode', 'sample'])
json_files = []
for root, dirs, files in os.walk(os.getcwd(), topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
for name in files:
if name.endswith('.json'):
json_files.append(os.path.join(root, name))
return json_files
def load_files(json_files):
"""works files"""
for js_file in json_files:
with open(js_file) as json_file:
loaded_json = json.load(json_file)
replace_key_value(loaded_json, os.path.basename(js_file))
def write_file(data_file, new_file_name):
"""writes the file"""
if not os.path.exists('converted'):
os.makedirs('converted')
with open('converted/' + new_file_name, 'w') as json_file:
json.dump(data_file, json_file)
def replace_key_value(js_file, js_file_name):
"""replace and initiate save"""
recursive_replace(js_file, SKEY, '')
# write_file(js_file, js_file_name)
def recursive_replace(data, match, repl):
"""search for needed value and replace its value"""
for key, value in data.items():
if value == match:
print data[key]
print "AHHHHHHHH"
elif isinstance(value, dict):
recursive_replace(value, match, repl)
# main
print "\n" + '- on ' + os.getcwd()
NEW_DIR = raw_input('Work dir (leave empty if current): ')
if not NEW_DIR:
print NEW_DIR
NEW_DIR = os.getcwd()
else:
print NEW_DIR
os.chdir(NEW_DIR)
# get_files()
JS_FILES = get_files()
print '- files on ' + os.getcwd()
# print "\n".join(JS_FILES)
SKEY = raw_input('Value to search: ')
RKEY = raw_input('Replacement value: ')
load_files(JS_FILES)
问题是我导航 json obj 的方式,因为该方法没有考虑它是字典还是列表(我相信...)。
所以为了回答我自己的问题,这里是我用来检查值的递归搜索:
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.iteritems():
if key == field:
print value
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
if SEARCH_KEY in result:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
if SEARCH_KEY in another_result:
fields_found.append(another_result)
return fields_found
# write_file(js_file, js_file_name)
希望这对某人有所帮助。
如标题中所述,我正在尝试制作一个简单的 py 脚本,可以从终端 运行 执行以下操作:
- 在当前工作目录和嵌套文件夹中查找所有 JSON 文件(这部分工作正常)
- 加载所述文件
- 递归搜索特定值或子字符串
- 如果该值匹配,则将其替换为用户新建立的值
- 完成后,将所有已修改的 json 文件保存到当前目录的 "converted" 文件夹中。
就是说,问题是当我尝试下面发布的递归搜索方法时,因为我对 python 还很陌生,我将不胜感激对这个问题的任何帮助,我想它是.. . 我正在使用的 json 文件或我正在使用的搜索方法。
简化问题,我搜索的值永远不会与 object 中的任何内容匹配,无论是键还是纯粹的字符串值。尝试了多种方法来执行递归搜索,但无法找到匹配项。
例如:考虑到示例 json,我想替换值 "selectable_parts" 或 "static_parts" 甚至更深的结构“1h_mod310_door_00”但是似乎我的搜索方法无法在 "object[object][children][0][children][5][name]" 中达到此值(希望这有帮助)。
示例 JSON:(https://drive.google.com/open?id=0B2-Bn2b0ujjVdW5YVGg3REg3OWs)
"""KEYWORD REPLACING MODULE."""
import os
import json
# functions
def get_files():
"""lists files"""
exclude = set(['.vscode', 'sample'])
json_files = []
for root, dirs, files in os.walk(os.getcwd(), topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
for name in files:
if name.endswith('.json'):
json_files.append(os.path.join(root, name))
return json_files
def load_files(json_files):
"""works files"""
for js_file in json_files:
with open(js_file) as json_file:
loaded_json = json.load(json_file)
replace_key_value(loaded_json, os.path.basename(js_file))
def write_file(data_file, new_file_name):
"""writes the file"""
if not os.path.exists('converted'):
os.makedirs('converted')
with open('converted/' + new_file_name, 'w') as json_file:
json.dump(data_file, json_file)
def replace_key_value(js_file, js_file_name):
"""replace and initiate save"""
recursive_replace(js_file, SKEY, '')
# write_file(js_file, js_file_name)
def recursive_replace(data, match, repl):
"""search for needed value and replace its value"""
for key, value in data.items():
if value == match:
print data[key]
print "AHHHHHHHH"
elif isinstance(value, dict):
recursive_replace(value, match, repl)
# main
print "\n" + '- on ' + os.getcwd()
NEW_DIR = raw_input('Work dir (leave empty if current): ')
if not NEW_DIR:
print NEW_DIR
NEW_DIR = os.getcwd()
else:
print NEW_DIR
os.chdir(NEW_DIR)
# get_files()
JS_FILES = get_files()
print '- files on ' + os.getcwd()
# print "\n".join(JS_FILES)
SKEY = raw_input('Value to search: ')
RKEY = raw_input('Replacement value: ')
load_files(JS_FILES)
问题是我导航 json obj 的方式,因为该方法没有考虑它是字典还是列表(我相信...)。
所以为了回答我自己的问题,这里是我用来检查值的递归搜索:
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.iteritems():
if key == field:
print value
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
if SEARCH_KEY in result:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
if SEARCH_KEY in another_result:
fields_found.append(another_result)
return fields_found
# write_file(js_file, js_file_name)
希望这对某人有所帮助。