tbag
tbag

Reputation: 1278

Java regex convert string to valid json string

I have a pretty long string that looks something like

{abc:\"def\", ghi:\"jkl\"}

I want to convert this to a valid json string like

{\"abc\":\"def\", \"ghi\":\"jkl\"}

I started looking at the replaceAll(String regex, String replacement) method on the string object but i'm struggling to find the correct regex for it.

Can someone please help me with this.

Upvotes: 3

Views: 2827

Answers (2)

MaxZoom
MaxZoom

Reputation: 7753

In this particular case the regex should look for a word that is proceeded with {, space, or , and not followed by "

String str = "{abc:\"def\", ghi:\"jkl\"}";
String regex = "(?:[{ ,])(\\w+)(?!\")";
System.out.println(str.replaceAll(regex, "\\\"$1\\\""));

DEMO and regex explanation

Upvotes: 2

leeyuiwah
leeyuiwah

Reputation: 7152

I have to make an assumption that the "key" and "value" consist of only "word characters" (\w) and there are no spaces in them.

Here is my program. Please also see the comments in-line:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexJson {

    public static void main(String[] args) {
        /*
         * Note that the input string, when expressed in a Java program, need escape
         * for backslash (\) and double quote (").  If you read directly
         * from a file then these escapes are not needed
         */
        String input = "{abc:\\\"def\\\", ghi:\\\"jkl\\\"}";

        // regex for one pair of key-value pair.  Eg: abc:\"edf\"
        String keyValueRegex = "(?<key>\\w+):(?<value>\\\\\\\"\\w+\\\\\\\")";
        // regex for a list of key-value pair, separated by a comma (,) and a space ( )
        String pairsRegex    = "(?<pairs>(,*\\s*"+keyValueRegex+")+)";
        // regex include the open and closing braces ({})
        String regex         = "\\{"+pairsRegex+"\\}";

        StringBuilder sb = new StringBuilder();

        sb.append("{");
        Pattern p1 = Pattern.compile(regex);
        Matcher m1 = p1.matcher(input);
        while (m1.find()) {
            String pairs = m1.group("pairs");
            Pattern p2 = Pattern.compile(keyValueRegex);
            Matcher m2 = p2.matcher(pairs);
            String comma = "";      // first time special
            while (m2.find()) {
                String key      = m2.group("key");
                String value    = m2.group("value");
                sb.append(String.format(comma + "\\\"%s\\\":%s", key, value));
                comma = ", ";       // second time and onwards
            }
        }
        sb.append("}");

        System.out.println("input is: " + input);
        System.out.println(sb.toString());
    }

}

The print out of this program is:

input is: {abc:\"def\", ghi:\"jkl\"}
{\"abc\":\"def\", \"ghi\":\"jkl\"}

Upvotes: 0

Related Questions