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

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

    
asked by anonymous 11.08.2014 / 18:35

2 answers

1

I did a brief search and found no "canonical" procedure other than text manipulation.

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

Below is an example 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 at IdeOne

    
12.08.2014 / 17:22
0

In its stackoverflow post in English the correct solution (in terms of elegance and good use of framework resources) is the one that proposed this section 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 respondent's credit is post

    
16.10.2014 / 13:18