How to extract json from a jsonp in a string in Scala

Question:

I'm using Scala and I have an http response like this:

_SS_MainSolrCallbackH(
  {
    response: {
      numFound: 1,
      start: 0,
      maxScore: 4.9338827,
      docs: [
        {
        tipo: "M",
        id: "mus1933196",a
        s: 4.9338827,
        u: "daniellaalcarpe",
        d: "lagrima-de-amor",
        dd: "",
        f: "202114_20130510215437.jpg",
        a: "Daniella Alcarpe",
        t: "Lágrima De Amor",
        g: "MPB"
        }
      ]
    },
    highlighting: {
      mus1933196: {
        titulo: [
          "Lágrima <b>De</b> <b>Amor</b>"
        ]
      }
    }
  }
)

If I try to parse this string as json, it will fail, because it's not exactly json. What's the best way to remove the _SS_MainSolrCallbackH( ) part of the string, leaving just the json hash?

Answer:

I did a brief search and didn't find a "canonical" procedure, but text manipulation.

Yes, it's a little ugly, but at least you can encapsulate the behavior in a function/method. Then, if the specification changes, just adjust the routine.

Below, an example of a generic function that retrieves the part of the String between the first and the last key:

def toJson(jsonp: String): String = {
    jsonp.substring(jsonp.indexOf('{'), jsonp.lastIndexOf('}') + 1);
}

Demo no IdeOne

Scroll to Top