Musaddique S
Musaddique S

Reputation: 1567

How can i add double quotes to look like json

i am having below string but i want to add double quotes in it to look like json

[
{
   LastName=abc, 
   FirstName=xyz, 
   [email protected], 
   IncludeInEmails=false
},
{ 
  LastName=mno, 
  FirstName=pqr, 
  [email protected], 
  IncludeInEmails=true
}
]

i want below output.

[
    {
       "LastName"="abc", 
       "FirstName"="xyz", 
       "EmailAddress"="[email protected]", 
       "IncludeInEmails"=false
    },
    { 
      "LastName"="mno", 
      "FirstName"="pqr", 
      "EmailAddress"="[email protected]", 
      "IncludeInEmails"=true
    }
    ]

i have tried some string regex. but didn't got. could any one please help.

String text= jsonString.replaceAll("[^\\{\\},]+", "\"$0\"");
System.out.println(text);

thanks

Upvotes: 7

Views: 14456

Answers (5)

Gaurav Panchal
Gaurav Panchal

Reputation: 11

    String json = new String("__json-without-whitespace-and-nextlines__");
    int n = json.length();
    StringBuilder result = new StringBuilder();
    for(int i=0; i<n; i++){
        char c = json.charAt(i);
        if(c == '='){
            // add closing quote for key; replace = with :
            result.append("\":");
            if(json.charAt(i+1) != '{' && json.charAt(i+1) != '[')// add opening quote for value 
                result.append("\"");
            if(json.charAt(i+1) == '}' || json.charAt(i+1) == ']' || json.charAt(i+1) == ',')// value empty
                result.append("\"");
            continue;
        }
        
        if(c == '{' || c == '[' && (json.charAt(i+1) != '{' && json.charAt(i+1) != '[')){
            // add opening bracket and then opening quote for key
            result.append(c); 
            result.append("\"");
        }
        else if(i < n-1 && (json.charAt(i+1) == ',' || json.charAt(i+1) == ']' || json.charAt(i+1) == '}') && c != ']' && c != '}'){
            // add closing quote for value
            result.append(c); 
            result.append("\"");
        }
        else if(c == ',' && json.charAt(i+1) != '{' && json.charAt(i+1) != '[')
            result.append(",\"");
        else result.append(c); 
        
        
    }
    System.out.println(result);

Upvotes: 1

Karthikeyan Velmurugan
Karthikeyan Velmurugan

Reputation: 631

Use the below code to get the output for your expection,

public class jsonTest {
	
	public static void main(String[] args){

		String test="[{ LastName=abc, FirstName=xyz, [email protected],IncludeInEmails=false},{ LastName=mno, FirstName=pqr, [email protected], IncludeInEmails=true}]";
	
		String reg= test.replaceAll("[^\\{\\},]+", "\"$0\"");
		
		String value=reg.replace("\"[\"{", "[{").replace("=","\"=\"").replace(" ","").replace("}\"]\"","}]").replace("\"true\"", "true").replace("\"false\"", "false");
		
		System.out.println("value :: "+value);	
	}
}

Upvotes: 0

Mahendra
Mahendra

Reputation: 1426

The regex way, similar to you have tried:

    String jsonString = "[ \n" + "{ \n" + "   LastName=abc,  \n" + "   FirstName=xyz,  \n"
            + "   [email protected],  \n" + "   IncludeInEmails=false \n" + "}, \n" + "{  \n"
            + "  LastName=mno,  \n" + "  FirstName=pqr,  \n" + "  [email protected],  \n" + "  Number=123,  \n"
            + "  IncludeInEmails=true \n" + "} \n" + "] \n";

    System.out.println("Before:\n" + jsonString);
    jsonString = jsonString.replaceAll("([\\w]+)[ ]*=", "\"$1\" ="); // to quote before = value
    jsonString = jsonString.replaceAll("=[ ]*([\\w@\\.]+)", "= \"$1\""); // to quote after = value, add special character as needed to the exclusion list in regex
    jsonString = jsonString.replaceAll("=[ ]*\"([\\d]+)\"", "= $1"); // to un-quote decimal value
    jsonString = jsonString.replaceAll("\"true\"", "true"); // to un-quote boolean
    jsonString = jsonString.replaceAll("\"false\"", "false"); // to un-quote boolean

    System.out.println("===============================");
    System.out.println("After:\n" + jsonString);

Upvotes: 3

nyname00
nyname00

Reputation: 2566

Since there are a lot of corner cases, like character escaping, booleans, numbers, ... a simple regex won't do.

You could split the input string by newline and then handle each key-value-pair separately

for (String line : input.split("\\R")) {
    // split by "=" and handle key and value
}

But again, you will have to handle char. escaping, booleans, ... (and btw, = is not a valid JSON key-value separator, only : is).

I'd suggest using GSON since it provides lenient parsing. Using Maven you can add it to your project with this dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.6.2</version>
</dependency>

You can then parse your input string using

String output = new JsonParser()
    .parse(input)
    .toString();

Upvotes: 1

vssk
vssk

Reputation: 465

Just use this library http://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1

Here is code for your example:

    JSONArray json =  new JSONArray();
    JSONObject key1 = new JSONObject();
    key1.put("LastName", "abc");
    key1.put("FirstName", "xyz");
    key1.put("EmailAddress", "[email protected]");
    key1.put("IncludeInEmails", false);        
    JSONObject key2 = new JSONObject();
    key2.put("LastName", "mno");
    key2.put("FirstName", "pqr");
    key2.put("EmailAddress", "[email protected]");
    key2.put("IncludeInEmails", true);  
    json.add(key1);
    json.add(key2);
    System.out.println(json.toString());    

Upvotes: 0

Related Questions