Scala flat JSON decoder with clear errors
Scala
def parseFlatJson(raw: String): Either[String, Map[String, String]] =
val text = raw.trim
if !text.headOption.contains('{') || !text.lastOption.contains('}') then
Left(s"JSON error: expected an object, got '${text.take(20)}'")
else
val body = text.slice(1, text.length - 1).trim
if body.isEmpty then Right(Map.empty[String, String])
else
val entries = body.split(',').toList.map(_.trim)
entries.foldLeft[Either[String, Map[String, String]]](Right(Map.empty[String, String])) {
case (Left(error), _) => Left(error)
case (Right(acc), entry) =>
val colon = entry.indexOf(':')
if colon < 0 then Left(s"JSON error: no colon in '$entry'")
else
val rawKey = entry.take(colon).trim
val rawValue = entry.drop(colon + 1).trim
val quoted = List(rawKey, rawValue).forall(v => v.length >= 2 && v.head == '"' && v.last == '"')
if !quoted then Left(s"JSON error: expected quoted key and value near '$entry'")
else Right(acc.updated(rawKey.substring(1, rawKey.length - 1), rawValue.substring(1, rawValue.length - 1)))
}