Simple way to add double quote in a JSON String

11,641

Demo

String text = "[Harry,[harry potter,harry and david]]";
text = text.replaceAll("[^\\[\\],]+", "\"$0\"");

System.out.println(text);

Output: ["Harry",["harry potter","harry and david"]]


Explanation:
If I understand you correctly you want to surround series of all non-[-and-]-and-, characters with double quotes. In that case you can simply use replaceAll method with regex ([^\\[\\],]+) in which which

  • [^\\[\\],] - represents one non character which is not [ or ] or , (comma)
  • [^\\[\\],]+ - + means that element before it can appear one or more times, in this case it represents one or more characters which are not [ or ] or , (comma)

Now in replacement we can just surround match from group 0 (entire match) represented by $0 with double brackets "$0". BTW since " is metacharacter in String (it is used to start and end string) we need to escape it if we want to create its literal. To do so we need to place \ before it so at the end it String representing "$0" needs to be written as "\"$0\"".

For more clarification about group 0 which $0 uses (quote from https://docs.oracle.com/javase/tutorial/essential/regex/groups.html):

There is also a special group, group 0, which always represents the entire expression.

Share:
11,641
JaskeyLam
Author by

JaskeyLam

blog: jaskey.github.io

Updated on June 17, 2022

Comments

  • JaskeyLam
    JaskeyLam almost 2 years

    I am trying to write something that returns some search suggestion result.

    Suppose I have an string like this :

    "[Harry,[harry potter,harry and david]]"
    

    The format is like [A_STRING,A_STRING_ARRAY_HERE].

    But I wany the output format to be like

    [ "Harry",["harry potter","harry and david"]]
    

    so that I can put it into the HTTP Response Body.

    Is there a simple way to do this, I don't want to add "" for a very single String from scratch .