简体   繁体   中英

Java : How to remove quotes from Json keys using 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!

I'd do:

  • find "([^"]+)":
  • replace $1:

Could you try it?

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

Regex remove quotes from keys

You use find by regex:

\"(\w+)\"\:

and replace with

$1:

In any editor

and in java will be

String res = str.replaceAll("\\\"(\\w+)\\\"\\:","\\\\$1:")

假设 jsonstr 中没有冒号 ( : ),除了作为键值分隔符,您也可以试验前瞻( (?=...)构造):

jsonStr.replaceAll("\"(?=.*:)", "");

尝试这样的事情:

jsonStr.replace(/\"/g, '');

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+)?)
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM