簡體   English   中英

如何在 JSON 文件中查找和替換所有出現的單詞並使用 python 保存生成的 JSON?

[英]How can I find and replace all occurrences of words in a JSON file and save the resulting JSON using python?

我有 2500 行 JSON 代碼,我需要用新值替換幾個值(20 位 id)。 這是一個快速查找和替換的方法,多虧了這個論壇,我昨天才開始工作。 現在,我注意到在 python 控制台中打印的代碼不是正確的 JSON,所以當我復制並粘貼它時,它會引發很多錯誤。 我試圖找到一種方法來加載 JSON 文件,運行查找和替換並將結果導出到新的 JSON 文件。

我首先嘗試在打開的情況下加載 JSON 文件並將其分配給一個變量,但是當我這樣做時,查找並替換 function 不起作用。 所以,我只是將原始代碼分配給一個變量。 但是,當我嘗試寫入/導出 JSON 文件時,它就不起作用了。 我嘗試了許多我在網上找到的解決方案,但所有的拋出錯誤要么沒有找到“str”或“write”對象,要么只是創建了空文件。

下面的代碼是我需要做的一個例子。 我不允許發布實際代碼。

import string
import csv
import json
from pprint import pprint

# These values need to be replaced in the code
# 1) Original View
# 2) View Source

valuesToReplace = ["Original View",
                   "View Source"
                   ]

# Replace/change these values
newValues = ["New Original View",
             "New View Source"
             ]

data = """{"menu": {
    "header": "SVG Viewer",
    "items": [
        {"id": "Open"},
        {"id": "OpenNew", "label": "Open New"},
        null,
        {"id": "ZoomIn", "label": "Zoom In"},
        {"id": "ZoomOut", "label": "Zoom Out"},
        {"id": "OriginalView", "label": "Original View"},
        null,
        {"id": "Quality"},
        {"id": "Pause"},
        {"id": "Mute"},
        null,
        {"id": "Find", "label": "Find..."},
        {"id": "FindAgain", "label": "Find Again"},
        {"id": "Copy"},
        {"id": "CopyAgain", "label": "Copy Again"},
        {"id": "CopySVG", "label": "Copy SVG"},
        {"id": "ViewSVG", "label": "View SVG"},
        {"id": "ViewSource", "label": "View Source"},
        {"id": "SaveAs", "label": "Save As"},
        null,
        {"id": "Help"},
        {"id": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}
"""

# If, instead, JSON file is loaded and assigned to variable, ReplaceValues throws an error
# with open(r"C:\jsonexample\codeExample.json") as dataFile:
#     data = json.load(dataFile)

def ReplaceValues(valuesToReplace, newValues, data):
    for i in range(len(newValues)):
        data = data.replace(valuesToReplace[i], newValues[i])
    return data

data = ReplaceValues(valuesToReplace, newValues, data)

pprint(data)

json.dump(data, r"C:\\jsonexample\\template\\newCode.json")

您似乎缺少在rw模式下打開文件(更多信息在這里)。 即使是json.dump()也需要這樣做來保存文件內容。

例子:

with open('out.json', 'w') as file:
    file.write(json.dumps(json_data))

但是對於您的情況,您可能根本不需要將其讀取為 JSON,因為它是一個通用的查找並且全部替換所有實例。

假設您的輸入文件就像您問題中的data字符串。

嘗試這個:

#replacements as key-value pairs
replacements = {
  'Original View':'New Original View', 
  'View Source':'New View Source'
  }

#Open the input file in read mode and get data as string
with open('your_file.json', 'r') as file:
  data = file.read()

#Replace all old value with new values
for old, new in replacements.items():
  data = data.replace(old, new)

#Open the output file in write mode and save
with open('output_file.json', 'w') as file:
  file.write(data)

輸出:

{"menu": {
  "header": "SVG Viewer",
  "items": [
      {"id": "Open"},
      {"id": "OpenNew", "label": "Open New"},
      null,
      {"id": "ZoomIn", "label": "Zoom In"},
      {"id": "ZoomOut", "label": "Zoom Out"},
      {"id": "OriginalView", "label": "New Original View"},
      null,
      {"id": "Quality"},
      {"id": "Pause"},
      {"id": "Mute"},
      null,
      {"id": "Find", "label": "Find..."},
      {"id": "FindAgain", "label": "Find Again"},
      {"id": "Copy"},
      {"id": "CopyAgain", "label": "Copy Again"},
      {"id": "CopySVG", "label": "Copy SVG"},
      {"id": "ViewSVG", "label": "View SVG"},
      {"id": "ViewSource", "label": "New View Source"},
      {"id": "SaveAs", "label": "Save As"},
      null,
      {"id": "Help"},
      {"id": "About", "label": "About Adobe CVG Viewer..."}
  ]
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM