Alex Fruzenshtein
Alex Fruzenshtein

Reputation: 3116

Scala: how to pass HTML as JSON value?

How to transfer HTML in JSON? According to JSON validation rules for Strings we need to escape ":

String: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.

So the question is how to process html string, in order to pass it to JSON and get a valid JSON doc in the end?

Let's consider this html:

<h1>Document</h1>
<p>Hello, welcome to wonderful web!</p>
<p>Start from visiting <a href="www.google.com">Google</a></p>

Applying .replace("\"", "\\\"") to a String with html content in Scala does not work.

I use spray-json .parseJson in order to validate the result.

Upvotes: 1

Views: 276

Answers (1)

import play.api.libs.json._

// basic types

val jsonString = Json.toJson("Fiver")
val jsonNumber = Json.toJson(4)
val jsonBoolean = Json.toJson(false)

// collections of basic types

val jsonArrayOfInts = Json.toJson(Seq(1, 2, 3, 4))
val jsonArrayOfStrings = Json.toJson(List("Fiver", "Bigwig"))

Upvotes: 1

Related Questions