Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : How to remove quotes from Json keys using regex

Tags:

java

regex

I need to strip the double quotes from a complex Json structure (object with children object and arrays in the hierarchy). I'm writing in Java (the app will run on Android).

I already have the string produced from a Json lib (Gson) and I am trying to strip the double quotes using regex instead of deserializing it back to an object and then serializing it without the double quotes in the key names.

I cannot find the right pattern or patterns to replace them.

example Json:

{
"key1":"value1",
"key2":"555f9ecd-2ced-42b7-b956-33e759bf8db1",
"key3":false,
"key4_parent":{
"child_key5":"Android",
"id":"7ae2facc-cdb3-7ae2-facccdb3bb86",
"name":"danny",
"bypassed":false
},
"object1":{
"deviceType":"Android",
"id":"7ae2facc-cdb3-7ae2-facccdb3bb86",
"base64val":"MENPSENJTFpZQzR3b1lvU1pQZTk=",
"name":"john"
},
"requiredLevel":"PUSH",
"level":"debug",
"status":1012,
"description":"Authentication in progress",
"objects":[
{
"deviceType":"Android",
"id":"7ae2facc-cdb3-7ae2-facccdb3bb86",
"base64val":"MENPSENJTFpZQzR3b1lvU1pQZTk=",
"name":"john"
},
{
"deviceType":"Android",
"id":"7ae2facc-cdb3-7ae2-facccdb3bb86",
"base64val":"MENPSENJTFpZQzR3b1lvU1pQZTk=",
"name":"john"
}
]
}

expected output :

{
key1:"value1",
key2:"555f9ecd-2ced-42b7-b956-33e759bf8db1",
key3:false,
key4_parent:{
child_key5:"Android",
id:"7ae2facc-cdb3-7ae2-facccdb3bb86",
name:"danny",
bypassed:false
},
object1:{
deviceType:"Android",
id:"7ae2facc-cdb3-7ae2-facccdb3bb86",
base64val:"MENPSENJTFpZQzR3b1lvU1pQZTk=",
name:"john"
},
requiredLevel:"PUSH",
level:"debug",
status:1012,
description:"Authentication in progress",
objects:[
{
deviceType:"Android",
id:"7ae2facc-cdb3-7ae2-facccdb3bb86",
base64val:"MENPSENJTFpZQzR3b1lvU1pQZTk=",
name:"john"
},
{
deviceType:"Android",
id:"7ae2facc-cdb3-7ae2-facccdb3bb86",
base64val:"MENPSENJTFpZQzR3b1lvU1pQZTk=",
name:"john"
}
]
}

I know that the output would not be a valid json. it's intended for easily searchable logging purposes.

any help would be greatly appreciated!

like image 408
FunkSoulBrother Avatar asked Mar 16 '17 12:03

FunkSoulBrother


People also ask

Can JSON key be without quotes?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.

How do you escape a quote in JSON?

Additionally, you must escape each double quotation mark that is inside the JSON structure by using a backslash before each double quotation mark.

How do you escape a double quote in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.

How do you escape a JSON string in Java?

You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.


3 Answers

I'd do:

  • find "([^"]+)":
  • replace $1:
like image 162
Toto Avatar answered Nov 04 '22 11:11

Toto


Could you try it?

jsonStr.replaceAll("\"(\\w+)\":", "$1:"));

Regex remove quotes from keys

like image 26
Roma Khomyshyn Avatar answered Nov 04 '22 12:11

Roma Khomyshyn


javascript For those who come looking for a javascript answer and who need compatibility with all valid JSON including keys containing escaped quotes (\"), colons (:), or whitespace (\s), here are 2 options.

.replace(/("(\\[^]|[^\\"])*"(?!\s*:))|"((\\[^]|[^\\"])*)"(?=\s*:)/g, '$1$3')

OR

function unquoteKeys(json) {
  return json.replace(/"(\\[^]|[^\\"])*"\s*:?/g, function (match) {
    if (/:$/.test(match)) return match.replace(/^"|"(?=\s*:$)/g, '');
    else return match;
  }
}

This type of function can be used to do almost anything with valid JSON.

function modifyJson(json) {
  return json.replace(/"(\\[^]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(\.\d+)?([eE][-+]?\d+)?/g, function (match) {
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        // match = Key with enclosing quotes & following colon (".*"\s*:)
      } else {
        // match = String (not key) with enclosing quotes (".*")
      }
    } else if (/true|false/.test(match)) {
      // match = Boolean value (true|false)
    } else if (/null/.test(match)) {
      // match = Null value (null)
    } else {
      // match = Number (-?\d+(\.\d+)?([eE][-+]?\d+)?)
    }
  });
}
like image 23
MorsBe Avatar answered Nov 04 '22 11:11

MorsBe