Reputation: 318
What's the easiest way to update a value in a JSON file, in Java, while preserving the original format. The JSON is large, nested, and has various kinds of JSON types.
From what I gathered, Java JSON libraries offer ways to "pretty print" but this overrides the original format.
Thanks in advance for any pointers!
Upvotes: 0
Views: 194
Reputation: 340350
If you are depending on the white-space in a JSON file being arranged a certain way, you are doing something wrong. By definition, white space does not matter in JSON.
So the proper way to update a JSON file is to simply re-write it. Use any library that meets the rules of JSON, or write it yourself.
To quote RFC 8259 section 2. JSON Grammar:
Insignificant whitespace is allowed before or after any of the six structural characters.
Note that JSON rules are quite loose and minimal. If you want strict detailed rules with robust enforcement by tooling, use XML and Schema instead.
Indeed, you may want to consider switching to XML given that your JSON is “large, nested”. JSON was intended to be used for relatively small and flat data. But in XML too, whitespace is irrelevant.
various kinds of JSON types
JSON has only about six data types: Number, String, Boolean, Array, Object, and null. Anything else is defined by your app, and such values should carry over as-is when re-writing another JSON file.
Again, if you want strict handling and enforcement of your custom data types, use XML & Schema instead. Don’t use a mallet when the job calls for a sledgehammer.
Upvotes: 0