Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save a JSON file with four spaces indentation using JSON.NET?

I need to read a JSON configuration file, modify a value and then save the modified JSON back to the file again. The JSON is as simple as it gets:

{
    "test": "init",
    "revision": 0
}

To load the data and modify the value I do this:

var config = JObject.Parse(File.ReadAllText("config.json"));
config["revision"] = 1;

So far so good; now, to write the JSON back to the file. First I tried this:

File.WriteAllText("config.json", config.ToString(Formatting.Indented));

Which writes the file correctly, but the indentation is only two spaces.

{
  "test": "init",
  "revision": 1
}

From the documentation, it looks like there's no way to pass any other options in using this method, so I tried modifying this example which would allow me to directly set the Indentation and IndentChar properties of the JsonTextWriter to specify the amount of indentation:

using (FileStream fs = File.Open("config.json", FileMode.OpenOrCreate))
{
    using (StreamWriter sw = new StreamWriter(fs))
    {
        using (JsonTextWriter jw = new JsonTextWriter(sw))
        {
            jw.Formatting = Formatting.Indented;
            jw.IndentChar = ' ';
            jw.Indentation = 4;

            jw.WriteRaw(config.ToString());
        }
    }
}

But that doesn't seem to have any effect: the file is still written with two space indentation. What am I doing wrong?

like image 763
Mark Bell Avatar asked Sep 11 '14 13:09

Mark Bell


People also ask

How do I indent in JSON?

Use four spaces for indentation (matching OpenStack conventions used in Python and shell scripts). Do not use tab characters in the code, always use spaces. Use one space after the name-separator (colon). Obey the formal JSON format; in particular, wrap strings in double (not single) quotes.

Do indentations matter in JSON?

JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible.

What is the correct format of a JSON file?

JSON File StructureJSON data is written in key/value pairs. The key and value are separated by a colon(:) in the middle with the key on the left and the value on the right. Different key/value pairs are separated by a comma(,). The key is a string surrounded by double quotation marks for example “name”.

What is Newtonsoft JSON formatting indented?

Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json. None − No special formatting is applied. This is the default. Indented − Causes child objects to be indented according to the Newtonsoft.


2 Answers

The problem is that you are using config.ToString(), so the object is already serialised into a string and formatted when you write it using the JsonTextWriter.

Use a serialiser to serialise the object to the writer instead:

JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, config);
like image 86
Guffa Avatar answered Oct 25 '22 11:10

Guffa


I ran into the same issue and found out that WriteRaw does not effect the indentation settings, however you can solve the issue using WriteTo on the JObject

using (FileStream fs = File.Open("config.json", FileMode.OpenOrCreate))
{
    using (StreamWriter sw = new StreamWriter(fs))
    {
        using (JsonTextWriter jw = new JsonTextWriter(sw))
        {
            jw.Formatting = Formatting.Indented;
            jw.IndentChar = ' ';
            jw.Indentation = 4;

            config.WriteTo(jw);
        }
    }
}
like image 38
Warnecke Avatar answered Oct 25 '22 13:10

Warnecke