python - How to find and replace a part of a value in json file

Python - How to find and replace a part of a value in json file

To find and replace a part of a value in a JSON file using Python, you can follow these steps:

  1. Read the JSON file.
  2. Parse the JSON content.
  3. Iterate through the JSON structure and modify the desired values.
  4. Write the modified JSON back to the file.

Here's an example using the json module:

import json # Read the JSON file file_path = 'your_json_file.json' with open(file_path, 'r') as file: data = json.load(file) # Iterate through the JSON structure and replace part of the value for key, value in data.items(): if isinstance(value, str): # Replace 'old_part' with 'new_part' in string values data[key] = value.replace('old_part', 'new_part') # Write the modified JSON back to the file with open(file_path, 'w') as file: json.dump(data, file, indent=2) print("Replacement completed.") 

Replace 'your_json_file.json', 'old_part', and 'new_part' with your actual JSON file path, the part you want to replace, and the new part you want to insert.

This example assumes a simple JSON structure where replacements are only needed in string values. If your JSON structure is more complex, you may need to adjust the code accordingly.

Also, keep in mind that reading and writing the entire JSON file might not be suitable for large files. In such cases, you might consider using more advanced libraries like ijson or reading the file line by line.

Examples

  1. Find and Replace String in JSON Value:

    • "Python find and replace string in JSON value example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) old_string = 'old_value' new_string = 'new_value' for key, value in data.items(): if isinstance(value, str): data[key] = value.replace(old_string, new_string) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Reads a JSON file, finds and replaces a specific string in string values, and writes the updated JSON back to the file.
  2. Find and Replace Nested Values in JSON:

    • "Python find and replace nested values in JSON example"
    • Code:
      import json def recursive_replace(obj, old_value, new_value): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_replace(value, old_value, new_value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item, old_value, new_value) elif isinstance(obj, str): obj = obj.replace(old_value, new_value) return obj with open('your_file.json', 'r') as file: data = json.load(file) data = recursive_replace(data, 'old_value', 'new_value') with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Recursively finds and replaces a specific string in nested values within a JSON file.
  3. Find and Replace Number in JSON Value:

    • "Python find and replace number in JSON value example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) old_number = 42 new_number = 99 def recursive_replace(obj): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_replace(value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item) elif obj == old_number: obj = new_number return obj data = recursive_replace(data) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Recursively finds and replaces a specific number in JSON values.
  4. Find and Replace Using Regular Expression:

    • "Python find and replace with regex in JSON example"
    • Code:
      import json import re with open('your_file.json', 'r') as file: data = json.load(file) old_pattern = re.compile(r'old_pattern') new_string = 'new_value' def recursive_replace(obj): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_replace(value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item) elif isinstance(obj, str): obj = old_pattern.sub(new_string, obj) return obj data = recursive_replace(data) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Uses regular expression to find and replace a pattern in JSON string values.
  5. Find and Replace Based on Key:

    • "Python find and replace based on key in JSON example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) target_key = 'key_to_replace' new_value = 'new_value' def recursive_replace(obj): if isinstance(obj, dict): for key, value in obj.items(): if key == target_key: obj[key] = new_value else: obj[key] = recursive_replace(value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item) return obj data = recursive_replace(data) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Recursively finds and replaces the value associated with a specific key in the JSON file.
  6. Find and Replace in Array of JSON Objects:

    • "Python find and replace in array of JSON objects example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) target_key = 'key_to_replace' new_value = 'new_value' for item in data: if target_key in item: item[target_key] = new_value with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Finds and replaces a specific value in a key across an array of JSON objects.
  7. Find and Replace in Nested JSON Array:

    • "Python find and replace in nested JSON array example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) target_key = 'key_to_replace' new_value = 'new_value' def recursive_replace(obj): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_replace(value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item) if target_key in item: item[target_key] = new_value return obj data = recursive_replace(data) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Recursively finds and replaces a specific value in a key within a nested JSON array.
  8. Find and Replace in JSON Array of Arrays:

    • "Python find and replace in JSON array of arrays example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) target_value = 'value_to_replace' new_value = 'new_value' for row in data: for i, value in enumerate(row): if value == target_value: row[i] = new_value with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Finds and replaces a specific value in a JSON array of arrays.
  9. Find and Replace Date in JSON Value:

    • "Python find and replace date in JSON value example"
    • Code:
      import json from datetime import datetime with open('your_file.json', 'r') as file: data = json.load(file) target_date_str = '2022-01-01' new_date_str = '2023-01-01' target_date = datetime.strptime(target_date_str, '%Y-%m-%d').date() new_date = datetime.strptime(new_date_str, '%Y-%m-%d').date() def recursive_replace(obj): if isinstance(obj, dict): for key, value in obj.items(): obj[key] = recursive_replace(value) elif isinstance(obj, list): for i, item in enumerate(obj): obj[i] = recursive_replace(item) elif isinstance(obj, str): try: date_value = datetime.strptime(obj, '%Y-%m-%d').date() if date_value == target_date: obj = new_date_str except ValueError: pass return obj data = recursive_replace(data) with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Recursively finds and replaces a specific date in date values within the JSON file.
  10. Find and Replace in JSON Array of Strings:

    • "Python find and replace in JSON array of strings example"
    • Code:
      import json with open('your_file.json', 'r') as file: data = json.load(file) target_string = 'string_to_replace' new_string = 'new_string' for i, value in enumerate(data): if value == target_string: data[i] = new_string with open('your_file.json', 'w') as file: json.dump(data, file, indent=2) 
    • Description: Finds and replaces a specific string in a JSON array of strings.

More Tags

having docker-toolbox liquid observable use-effect ssms proxy rhino-mocks mod-rewrite shell

More Programming Questions

More Dog Calculators

More Pregnancy Calculators

More Biochemistry Calculators

More Electronics Circuits Calculators