5

I'm getting a garbled JSON string from a HTTP request, so I'm looking for a temp solution to select the JSON string only.

The request.params() returns this:

[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,
callback=jQuery1707229194729661704_1329793018352

I would like everything from the start of the '{' to the end of the '}'.

I found lots of examples of doing similar things with other languages, but the purpose of this is not to only solve the problem, but also to learn Scala. Will someone please show me how to select that {....} part?

2 Answers 2

5

Regexps should do the trick:

"\\{.*\\}".r.findFirstIn("your json string here")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jens, apologies for not being able to choose two answers. Yours is perfect also.
4

As Jens said, a regular expression usually suffices for this. However, the syntax is a bit different:

"""\{.*\}""".r

creates an object of scala.util.matching.Regex, which provides the typical query methods you may want to do on a regular expression.

In your case, you are simply interested in the first occurrence in a sequence, which is done via findFirstIn:

scala> """\{.*\}""".r.findFirstIn("""[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,callback=jQuery1707229194729661704_1329793018352""")
res1: Option[String] = Some({"insured_initials":"Tt","insured_surname":"Test"})

Note that it returns on Option type, which you can easily use in a match to find out if the regexp was found successfully or not.

Edit: A final point to watch out for is that the regular expressions normally do not match over linebreaks, so if your JSON is not fully contained in the first line, you may want to think about eliminating the linebreaks first.

1 Comment

Short comment on "eliminating linebreaks": better use (?s) modifier - so . would match newline characters as well. Reference on regexps

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.