Json read, write and pretty print

Python

Elements in {} is dictionary and elements in [] is array. For dictionary just access element by name, for array it needs to access using index number.

Note the json.dumps method converts a json object to string for printing. The json.dump, without s, is for loading string into a json object.


import json


with open('input.txt') as f:

    json_file = json.load(f)

    

json_file['datasource'] = 'microsoft sql server'

json_file['targets'][0]['name'] = 'abc'

json_file['targets'][0]['values'] = [1, 2, 3, 4]


with open('output.txt', 'w') as f:

    f.write(json.dumps(json_file, indent=4, sort_keys=True))  


C#

In C# the NewtonSoft.Json or Json.net is the library to use.

To convert a Json String into a JSON object, it uses the DeserializeObject method.

To convert a  JSON object back to JSon string, it uses the SerializeObject method.

Below is just an example of calling the methods.

Similar to Python, to read a dictionary element, just use ['key name']. To read an item from an array, uses the [index number].

To assign a value to a JSON object, if it is a string value, just assign it. But if it is an array/list, it needs to convert the array to JArray before assigning.

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;


var json_dict= JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json_string);

var a = json_dict["key name"] ;

var b = json_dict["key name"][0]["another key name"][1];



json_dict["key name"] = new JArray(attributes);       // attributes is a list

json_dict["key name"][0]["key name 2"] = 'abc'


var output_string = JsonConvert.SerializeObject(json_dict, Formatting.Indented);