Is there a way to replace brackets in a string inside a .json file?

I am working on an app that has a huge .json database, a lot of the strings I need in the .json file have curly brackets (“{“, “}”) inside them, which I do not want, like this:

[
      {
        "name": "Whatever",
        "entries": [
          "If something something {28} + {41.6} something"
        ]
      }
]

And I need to get the string as “If something something 28 + 41.6 something”.

I remove them by fetching the string I need and using this method:

public String formatText(String text) {

    String newtext = text.replaceAll("\{", "").replaceAll("\}", "");

   return newtext;
}

That works but makes everything really slow. I had other characters in the file, like “@”, that I had no problem removing in a text editor by selecting all of them and replacing by the empty string. But if I use the same logic with the curly brackets it will also remove the json object brackets.

Anyone can think of a way to edit this file and remove only the brackets inside the strings?

(I’ve thought of making a method that copies the strings, formats them and send them to a new .json, but that would be really innefective timewise, because there is a lot of different values inside every object.)

Answer

If you wanna use the find/replace functionality of text editors – using IDE like intelij – there is an option to replace stuff by regex. E.g. this (?=S.)({|}) should cover your case with braces in string only, while not touching json syntax braces. If you have other unique cases – they should be included in regex. Example – https://regex101.com/r/wbIgKX/1

Though, I would propose to create a proper json parser class specifically to deal with your stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *