Replace Whitespace in Json Keys

How can I replace spaces in a JSON object keys dynamically using Javascript?

Here's complete code using forEach.

The steps are same as Quentin has stated in his answer

  1. Copy the value
  2. Remove the key-value from the object
  3. Add new item with new value in the object

var arr = [{  "FIRST NAME": "Philip",  "LAST NAME": "Rivers",  "NUMBER": "17",  "GPA": "1.0",  "OLD_FACTOR": "8",  "NICENESS": "1"}, {  "FIRST NAME": "Peyton",  "LAST NAME": "Manning",  "NUMBER": "18",  "GPA": "4.0",  "OLD_FACTOR": "5000",  "NICENESS": "5000"}];

// Iterate over arrayarr.forEach(function(e, i) { // Iterate over the keys of object Object.keys(e).forEach(function(key) { // Copy the value var val = e[key], newKey = key.replace(/\s+/g, '_'); // Remove key-value from object delete arr[i][key];
// Add value with new key arr[i][newKey] = val; });});
console.log(arr);document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>

Replace whitespace in JSON keys

Replacing Keys

The following code uses Google's JSON parser to extract keys, reformat them, and then create a new JSON object:

public static void main(String[] args) {
String testJSON = "{\"TestKey\": \"TEST\", \"Test spaces\": { \"child spaces 1\": \"child value 1\", \"child spaces 2\": \"child value 2\" } }";
Map oldJSONObject = new Gson().fromJson(testJSON, Map.class);
JsonObject newJSONObject = iterateJSON(oldJSONObject);

Gson someGson = new Gson();
String outputJson = someGson.toJson(newJSONObject);
System.out.println(outputJson);
}

private static JsonObject iterateJSON(Map JSONData) {
JsonObject newJSONObject = new JsonObject();
Set jsonKeys = JSONData.keySet();
Iterator<?> keys = jsonKeys.iterator();
while(keys.hasNext()) {
String currentKey = (String) keys.next();
String newKey = currentKey.replaceAll(" ", "_");
if (JSONData.get(currentKey) instanceof Map) {
JsonObject currentValue = iterateJSON((Map) JSONData.get(currentKey));
newJSONObject.add(currentKey, currentValue);
} else {
String currentValue = (String) JSONData.get(currentKey);
newJSONObject.addProperty(newKey, currentValue);
}
}
return newJSONObject;
}

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:

public static void removeJSONSpaces(JSONArray theJSON) {
for (int i = 0; while i < theJSON.length(); i++) {
if (theJSON.get(i) instanceof JSONArray) {
currentJSONArray = theJSON.getJSONArray(i);
removeJSONSpaces(currentJSONArray);
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}
}

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:

public static void removeJSONSpaces(JSONObject theJSON) {

jObject = new JSONObject(theJSON.trim());
Iterator<?> keys = jObject.keys();

while(keys.hasNext()) {
String key = (String)keys.next();
if (jObject.get(key) instanceof JSONObject) {
removeJSONSpaces(jObject.get(key))
} else {
currentEntry = theJSON.getString(i);
fixedEntry = currentEntry.replace(" ", "_");
currentJSONArray.put(i, fixedEntry);
}
}

}

You can read more about JSONObjects here

Replace whitespace in JSON keys with regex

You can use this regex which targets space present only in keys,

\s(?=[^,"]*"\s*:)

Demo

Javascript demo,

s = '{"december 25":"ho ho ho", "all I want": "christmas", "ids":["sandy","claws"]}';console.log('Before:', s);console.log('After:', s.replace(/\s(?=[^,"]*"\s*:)/g, '_'));

Regex to remove spaces from Key but not Value

You can probably try the following expression as a quick fix granted the JSON you need to fix is in the format you have shown (it might fail to work with other JSONs):

\s(?=[^"]*":\s*")

See the regex demo

Details

  • \s - a whitespace
  • (?=[^"]*":\s*") - a positive lookahead that, immediately to the right of the current position, requires
    • [^"]* - zero or more chars other than "
    • ": - ": string
    • \s* - 0+ whitespaces
    • " - a double quote.

remove whitespace inside json object key value pair

Assign the trimmed value to the specific user[key]:

var user = { first_name: "CSS", last_name: " H ", age: 41, website: "java2s.com" };
for (var key in user) { user[key] = user[key].toString().trim() console.log(key+"-->"+user[key]);}

Remove spaces in Json keys

You can use JSON.stringify(), JSON.parse(), String.prototype.replace() with RegExp /\s(?=\w+":)/g to match space character followed by one or more word characters followed by " followed by :