如何使用Python更新并添加JSON文件中字典的键值对
Solution to Update and Add Key-Value Pairs in JSON File
Hey there! Let's get your JSON file updated exactly how you want it. You've already nailed the initial steps—loading the JSON data and defining the key-value pairs you need. Here's how to wrap it up perfectly:
Step-by-Step Breakdown
- Add
site_idto thesite_postsection: We'll directly insert the new key-value pair here using the value from yourdctvariable. - Update
plant_postwith new values: Use Python's built-in dictionaryupdate()method to replace the emptysite_idandplant_identries with your desired values. - Write changes back to the file: Save the modified data with proper indentation to keep the JSON structure clean and readable.
Complete Working Code
import json # Load the existing JSON data from hi.json with open('hi.json') as f: data = json.load(f) # Define the key-value pairs we need to update/add dct = {"site_id":"123","plant_id":"456"} # Add site_id to the site_post dictionary data['site_post']['site_id'] = dct['site_id'] # Update plant_post with both key-value pairs from dct data['plant_post'].update(dct) # Write the modified data back to hi.json (with indentation for readability) with open('hi.json', 'w') as f: json.dump(data, f, indent=2)
What Each Part Does
data['site_post']['site_id'] = dct['site_id']: This line directly adds thesite_idkey to thesite_postsection, setting its value to "123" as specified.data['plant_post'].update(dct): Theupdate()method merges yourdctinto theplant_postdictionary, automatically overwriting the emptysite_idandplant_idvalues with your new ones.json.dump(data, f, indent=2): Writes the updated data back to the file, and theindent=2parameter ensures the JSON stays formatted neatly just like your expected output.
After running this code, your hi.json will match exactly the result you shared!
内容的提问来源于stack exchange,提问作者Divyank
相关产品推荐
相关产品推荐

