I am thinking of a best solution to replace all the whitespaces in JSON keys with underscore.
{
"Format": "JSON",
"TestData": {
"Key with Spaces in it": {
"And Again": {
"Child_Key1": "Financial",
"Child_Key2": null
},
.........
.....
I want the above to be converted as shown below:
{
"Format": "JSON",
"TestData": {
"Key_with_Spaces_in_it": {
"And_Again": {
"Child_Key1": "Financial",
"Child_Key2": null
},
.........
.....
Any suggestions ?
Does any Java library have any predefined function to do this ?
Try this one:
replace the WhiteSpace with "_"
}
You can just read in each of the keys/values then use the
String replace(String oldString, String newString)
method.http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Remove only the white space on the strings in jason code not all white space on jason code
I am using gson library in order to remove bad keys from json string because I want to create the AVRO file of the json. Keys with spaces or non Alphanumeric are not acceptable from Avro so I have to sanitize input first.
The above snippet removes whitespaces and character $ from all keys (iterative). I assume my json string is JsonObject.
Check out a small sample code that I have used.
Replacing Keys
The following code uses Google's JSON parser to extract keys, reformat them, and then create a new JSON object:
You can read more about GSON here.
Replacing Values
Depending on how your JSON data is set up, you might need to switch JSONArray with JSONObject.
JSONArrays begin and end with
[]
, while JSONObjects begin and end with{}
In short, these methods will travel over an entire array/object and replace any spaces with underscores. They're recursive, so they will dive into child JSONArrays/JSONObjects.
If the JSON data is encoded as a Java JSONArray, you can do the following:
In short, this method will travel over an entire array and replace any spaces with underscores. It's recursive, so it will dive into child JSONArrays.
You can read more about JSONArrays here
If the data is encoded as a JSONObject, you'd want to do something like:
You can read more about JSONObjects here