How to extract json from a jsonp in a Scala string

Asked

Viewed 87 times

3

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 is not exactly a json. What is the best way to remove the part _SS_MainSolrCallbackH( ) of the string, leaving only the json hash?

  • Hello, Daniel. Is this part you want to remove always the same or similar? Have you ever thought about just using substring?

  • 1

    actually it’s always the same, but I wanted to do it in a generic way. I solved it temporarily with string.replace("_Ss_mainsolrcallbackh(", ""). take(string.size - 2) but it looks kind of ugly...

2 answers

1

I did a brief research and did not find a "canonical" procedure, but text manipulation.

Yes, it is a bit ugly, but at least you can encapsulate the behavior in a function/method. So if the specification changes, just adjust the routine.

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

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

Demo no Ideone

0

In your English stackoverflow post the correct solution (in terms of elegance and good use of the framework’s resources) is the one that proposed this stretch in scala

scala> val body = "_Ss_mainsolrcallbackh( n n)" body: String = _Ss_mainsolrcallbackh( )

scala> val jsonStr = body.lines.toList.tail.init.mkString jsonStr: String =

the credit is of the respondent in post

Browser other questions tagged

You are not signed in. Login or sign up in order to post.