使用Python删除JSON文件中的未更新文本/对象

时间:2019-04-27 02:58:52

标签: python json python-3.x

此脚本使用用户输入来更新json文件中的代码,但不替换占位符文本onload='window.print()' x是数字(1、5)。我想删除脚本没有用用户输入更新的占位符文本。它以前曾经工作过,但现在没有了,我可以找出原因。任何帮助都将受到欢迎!谢谢!

代码:

Microsoft Print to Pdf

JSON文件:

Screenshot URL X

1 个答案:

答案 0 :(得分:2)

这行吗?

import json
file_name = "test.json"
with open(file_name) as fh:
    full_data = json.load(fh)

    # Dig into the data to find the screenshots
    screen_shots = full_data['tabs'][0]['views'][1]['screenshots']

    # Loop over each screen shot, updating each one
    print("Press return/enter to enter another url or press it again with nothing entered to stop asking and continue the script.")
    for number, screen_shot in enumerate(screen_shots):
        new_url = input("Screnshot URL: ").strip()

        if new_url:
            # Updating the data here will also update the 'full_data' object
            # as we are just referencing a part of it, not making copies
            screen_shot.update({"url": new_url, "fullSizeURL": new_url})
        else:
            break

    # Remove all entries which we did not update
    screen_shots = screen_shots[:number]
    full_data['tabs'][0]['views'][1]['screenshots'] = screen_shots #-> this lines removes the placeholder text that is not updated by the user

    # Save the data
    with open(file_name, 'w') as fh:
        json.dump(full_data, fh, indent=4)