【问题标题】:Python 2.7: Load a JSON file search for a value, replace it, and save as new JSONPython 2.7:加载一个 JSON 文件搜索一个值,替换它,并保存为新的 JSON
【发布时间】:2017-06-12 20:44:40
【问题描述】:

正如标题中提到的,我正在尝试制作一个可以从终端运行的简单 py 脚本来执行以下操作:

  • 在当前工作目录和嵌套文件夹中查找所有 JSON 文件(这部分效果很好)
  • 加载上述文件
  • 递归搜索它们以查找特定值或子字符串
  • 如果值匹配,则将其替换为用户建立的新值
  • 完成后,将所有修改后的 json 文件保存到当前目录中的“已转换”文件夹中。

也就是说,问题是当我尝试下面发布的递归搜索方法时,因为我对 python 非常陌生,我希望能在这个问题上提供任何帮助,我想它是什么......要么是我的 json 文件正在使用或正在使用的搜索方法。

为了简化问题,我搜索的值永远不会与对象内的任何内容匹配,无论是键还是纯字符串值。尝试了多种方法来执行递归搜索,但找不到匹配项。

例如:考虑到示例 json,我想在结构“1h_mod310_door_00”中替换值“selectable_parts”或“static_parts”甚至更深,但似乎我的搜索方法无法在“ 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 文件中搜索对象并尝试将值与搜索参数匹配时,它永远不会匹配。我可以导航和打印对象,但该值与要搜索的参数不匹配。

标签: json python-2.7 search recursion load


【解决方案1】:

问题在于我导航 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)

希望这对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2012-06-14
    • 2021-03-18
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    相关资源
    最近更新 更多