Skip to content

Commit

Permalink
encodeJsonArrayPipeline produces incorrect JSON when stream is empty (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
amsavchuk authored May 13, 2024
1 parent 3d682cf commit a1c964e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,20 @@ trait JsonEncoderPlatformSpecific[A] { self: JsonEncoder[A] =>
)
}
}
writeWriter <- ZIO.succeed(new WriteWriter(writer))
writeWriter <- ZIO.succeed(new WriteWriter(writer))
hasAtLeastOneElement <- Ref.make(false)
push = { (is: Option[Chunk[A]]) =>
val pushChars = chunkBuffer.getAndUpdate(c => if (c.isEmpty) c else Chunk())

is match {
case None =>
ZIO.attemptBlocking(writer.close()) *> pushChars.map { terminal =>
endWith.fold(terminal) { last =>
// Chop off terminal delimiter
(if (delimiter.isDefined) terminal.dropRight(1) else terminal) :+ last
}
ZIO.attemptBlocking(writer.close()) *> pushChars.flatMap { terminal =>
hasAtLeastOneElement.get.map(nonEmptyStream =>
endWith.fold(terminal) { last =>
// Chop off terminal delimiter if stream is not empty
(if (delimiter.isDefined && nonEmptyStream) terminal.dropRight(1) else terminal) :+ last
}
)
}

case Some(xs) =>
Expand All @@ -64,7 +67,7 @@ trait JsonEncoderPlatformSpecific[A] { self: JsonEncoder[A] =>
for (s <- delimiter)
writeWriter.write(s)
}
} *> pushChars
} *> hasAtLeastOneElement.set(true).when(xs.nonEmpty) *> pushChars
}
}
} yield push
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import testzio.json.data.googlemaps._
import testzio.json.data.twitter._
import zio.Chunk
import zio.json.ast.Json
import zio.stream.ZStream
import zio.stream.{ ZSink, ZStream }
import zio.test.Assertion._
import zio.test.{ ZIOSpecDefault, assert, _ }

Expand Down Expand Up @@ -75,6 +75,14 @@ object EncoderPlatformSpecificSpec extends ZIOSpecDefault {
} yield {
assert(xs.mkString)(equalTo("""[{"id":1},{"id":2},{"id":3}]"""))
}
},
test("encodeJsonArrayPipeline, empty stream") {
val emptyArray = ZStream
.from(List())
.via(JsonEncoder[String].encodeJsonArrayPipeline)
.run(ZSink.mkString)

assertZIO(emptyArray)(equalTo("[]"))
}
),
suite("helpers in zio.json")(
Expand Down
10 changes: 10 additions & 0 deletions zio-json/shared/src/test/scala/zio/json/ast/JsonSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,16 @@ object JsonSpec extends ZIOSpecDefault {
assert(posts.get(combined))(
isRight(equalTo(Json.Str("foo")))
)
},
test(">>>, identity") {
val obj = Json.Obj("a" -> Json.Num(1))

val fieldA = JsonCursor.field("a")
val identity = JsonCursor.identity

val num = obj.get(fieldA >>> identity)

assert(num)(isRight(equalTo(Json.Num(1))))
}
),
suite("intersect")(
Expand Down

0 comments on commit a1c964e

Please sign in to comment.