3

I am using Scala language and I have a response body like this:

_SS_MainSolrCallbackH(
  {
    response: {
      numFound: 1,
      start: 0,
      maxScore: 4.9338827,
      docs: [
        {
        tipo: "M",
        id: "mus1933196",
        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 as a json, it fails, because it is not actually a json. What is the best way to remove the _SS_MainSolrCallbackH( ) part of the string, leaving only the json hash?

1
  • added update for regex Commented Aug 28, 2014 at 11:54

2 Answers 2

1

A simple approach for an input str: String includes,

str.stripPrefix("_SS_MainSolrCallbackH(").stripSuffix(")")

which strips out the padding. For usability, consider for instance

def stripPadding(str: String, padding: String) =
  str.stripPrefix(padding+"(").stripSuffix(")")

Update

Using regular expressions, try

val re = """(?s)_SS_MainSolrCallbackH\((.*)\)""".r
re: scala.util.matching.Regex = (?s)_SS_MainSolrCallbackH\((.*)\)

scala> val re(x) = a
x: String =
"
  {
    response: {... } 
  }
"
Sign up to request clarification or add additional context in comments.

Comments

0

It depends on what data type your response body is, and how robust you want to be against formatting changes (no line breaks, change of text "_SS_MainSolrCallbackH", extra lines around your posted text).

Assuming your response body is of type String, and the wrapping text around your body will always look as posted, it is as simple as removing the first and last line:

scala> val body = "_SS_MainSolrCallbackH(\n<some JSON>\n)"
body: String = 
_SS_MainSolrCallbackH(
<some JSON>
)

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

If you need a more sophisticated solution, please provide more details in your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.