Trim white spaces in both Object key and value recursively

后端 未结 8 1970
一生所求
一生所求 2020-12-05 05:53

How do you trim white spaces in both the keys and values in a JavaScript Object recursively?

I came across one issue in which I was trying to \"clean\" a user suppli

8条回答
  •  鱼传尺愫
    2020-12-05 06:17

    Similar to epascarello's answer. This is what I did :

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    ........
    
    public String trimWhiteSpaceAroundBoundary(String inputJson) {
        String result;
        final String regex = "\"\\s+|\\s+\"";
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(inputJson.trim());
        // replacing the pattern twice to cover the edge case of extra white space around ','
        result = pattern.matcher(matcher.replaceAll("\"")).replaceAll("\"");
        return result;
    }
    

    Test cases

    assertEquals("\"2\"", trimWhiteSpace("\" 2 \""));
    assertEquals("2", trimWhiteSpace(" 2 "));
    assertEquals("{   }", trimWhiteSpace("   {   }   "));
    assertEquals("\"bob\"", trimWhiteSpace("\" bob \""));
    assertEquals("[\"2\",\"bob\"]", trimWhiteSpace("[\"  2  \",  \"  bob  \"]"));
    assertEquals("{\"b\":\"bob\",\"c c\": 5,\"d\": true }",
                  trimWhiteSpace("{\"b \": \" bob \", \"c c\": 5, \"d\": true }"));
    

提交回复
热议问题