Change values in JSON file (writing files)
Here's a simple & cheap way to do it (assuming .NET 4.0 and up):
string json = File.ReadAllText("settings.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["Bots"][0]["Password"] = "new password";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("settings.json", output);
The use of dynamic
lets you index right into json objects and arrays very simply. However, you do lose out on compile-time checking. For quick-and-dirty it's really nice but for production code you'd probably want the fully fleshed-out classes as per @gitesh.tyagi's solution.
Update property in json file with C#
you need to save the complete JSON when you update a property of an element of the array
static void Main(string[] args)
{
const string jsonPath = @"C:\Logs\recordRoot.json";
var loanRecordRoot = JsonConvert.DeserializeObject<LoanRecordRoot>(File.ReadAllText(jsonPath));
foreach (var record in loanRecordRoot.LoanRecords)
{
if (record.Completed == "false")
{
if (ManipulateEncompass(rec.LoanGUID, rec.ProcessType))
{
record.Completed = "true";
}
}
}
//Save Json
var json = JsonConvert.SerializeObject(loanRecordRoot, Formatting.Indented);
File.WriteAllText(jsonPath, json);
}
Update specific value in JSON file
Using NewtonSoft, I once made a flatten function to analyse json files of any depth:
IEnumerable<JProperty> Flatten(JToken token)
{
return token.Children<JProperty>().Concat(
token.Children().SelectMany(t => Flatten(t)))
.Where(t => t.Value is JValue);
}
It returns a flat listing of all "endpoint" JsonProperty
s in a file (say: all "xyx" : primitive value
entries). Using it you can simply deserialize your Json, find all "email" properties and set their value to null
:
var jobj = JsonConvert.DeserializeObject<JObject>(getJson());
var flattened = Flatten(jobj);
foreach (var jprop in flattened.Where(t => t.Name == "email"))
{
jprop.Value = null;
}
var json = JsonConvert.SerializeObject(jobj).Dump();
Result for the "more complicated" json (with one deeper email added to make it more fun):
{
"reservations": [
{
"id": "111",
"bookingId": "",
"status": "",
"checkInTime": "",
"checkOutTime": "",
"property": {
"id": "",
"code": "",
"name": ""
},
"primaryGuest": {
"firstName": "",
"middleInitial": "",
"lastName": "",
"email": null,
"phone": "",
"address": {
"email": null,
"addressLine1": "",
"postalCode": "",
"city": "",
"countryCode": ""
}
},
"booker": {
"firstName": "",
"middleInitial": "",
"lastName": "",
"email": null,
"phone": ""
}
}
]
}
how to change the value of json file after comparing its element to another json file?
Below code should solve your issue of reading, logic and writing into your file.
'use strict';
const fs = require('fs');
let rawdata_one = fs.readFileSync('one.json');
let rawdata_two = fs.readFileSync('two.json');
let onedata = JSON.parse(rawdata_one);
let twodata = JSON.parse(rawdata_two);
onedata.forEach(
function(obj){
let ob = twodata.findIndex( o => o.id == obj.projectId );
if(ob != -1){
twodata[ob].completedCount = obj.completedCount;
}
}
)
let data = JSON.stringify(twodata);
fs.writeFileSync('two.json', data);
This write will overwrite your two.json with the updated data.
You can also read the json file using require('one.json'). However, it can be done only once in your entire code.
How to modify the multiple values in the JSON file using python
The code works as expected if you have resolved the variable name difference.
Further, I would also suggest to open the file using context manager with
so that it gets closed automagically when the with
block is exited.
import json, os
with open(".\example.json", 'r') as f:
data = json.load(f)
for feature in data['images']:
feature['file_name'] = os.path.basename(feature["file_name"])
print(data)
Output:
Data in json
file:
{'images': [{'id': 1, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1110.jpg', 'height': 3024, 'width': 4032}, {'id': 2, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1111.jpg', 'height': 3024, 'width': 4032}, {'id': 3, 'file_name': 'Folder1/Folder2/Folder3/Folder4/1112.jpg', 'height': 3024, 'width': 4032}]}
Formatted data:
{'images': [{'id': 1, 'file_name': '1110.jpg', 'height': 3024, 'width': 4032}, {'id': 2, 'file_name': '1111.jpg', 'height': 3024, 'width': 4032}, {'id': 3, 'file_name': '1112.jpg', 'height': 3024, 'width': 4032}]}
Working on .json files (read/write/change) on-the-fly with Python
I would recommend you to just use the json library. Read the file once and do occasionally a save, let's say every five minutes.
Maybe you want to create a new class in a singleton pattern. This will ensure that you have one object that holds the current up-to-date information and only this object can update the file.
Here is a quick sketch on how this class may look like:
# SaveFileHandler.py
import json
class _SaveFileHandler:
def __init__(self):
self._data = {}
self._path = ""
def read(self, path):
self._path = path
with open(path) as file:
self._data = json.load(file)
def write(self):
with open(self._path) as file:
json.dump(self._data, file)
# now for every value you want data to have do the following
# it allows you to check the value for errors and makes the usage more readable
@property
def key(self):
return self._data["key"]
@key.setter
def key(self, value):
self._data["key"] = value
# the is the only object you will ever use
save_file = _SaveFileHandler()
You can also read the save file directly in the init, this will make sure your data is always available.
Related Topics
Getting Serial Port Information
How to Compare Values of Generic Types
Jtoken: Get Raw/Original JSON Value
How to Invoke a UI Method from Another Thread
How to Select Min and Max Values of a Column in a Datatable
Send HTML Email via C# with Smtpclient
How to Get a List of All Routes in ASP.NET Core
How to Serialize Nested Properties to My Class in One Operation with JSON.Net
How to Run Visual Studio Without Plugin and All Third Party Feature
How to Implement a Custom Razorviewengine to Find Views in Non-Standard Locations
Where's the Datetime 'Z' Format Specifier
Why Is Array.Length an Int, and Not an Uint
How to Use Reflection to Call Method by Name
Why Can't I Use System.Io.File Methods in an MVC Controller
The Provided Uri Scheme 'Https' Is Invalid; Expected 'Http'. Parameter Name: Via
Question Mark and Colon in Statement. What Does It Mean
No Connection String Named 'Myentities' Could Be Found in the Application Config File