Skip to content

Commit 9aeaf70

Browse files
committed
pkg/encoding/json: implement UnmarshalStream
Signed-off-by: Marcel van Lohuizen <mpvl@golang.org> Change-Id: Id8484437779dba22c9b01220a23356fdd639f8a0 Signed-off-by: Marcel van Lohuizen <mpvl@golang.org> Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/532281 Unity-Result: CUEcueckoo <cueckoo@cuelang.org> TryBot-Result: CUEcueckoo <cueckoo@cuelang.org> Reviewed-by: Paul Jolly <paul@myitcv.io>
1 parent 480b28b commit 9aeaf70

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

pkg/encoding/json/manual.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"bytes"
1919
"encoding/json"
2020
"fmt"
21+
"io"
2122

2223
"cuelang.org/go/cue"
2324
"cuelang.org/go/cue/ast"
@@ -92,6 +93,26 @@ func MarshalStream(v cue.Value) (string, error) {
9293
return buf.String(), nil
9394
}
9495

96+
// UnmarshalStream parses the JSON to a CUE instance.
97+
func UnmarshalStream(data []byte) (ast.Expr, error) {
98+
var r cue.Runtime
99+
d := cuejson.NewDecoder(&r, "", bytes.NewReader(data))
100+
101+
a := []ast.Expr{}
102+
for {
103+
x, err := d.Extract()
104+
if err == io.EOF {
105+
break
106+
}
107+
if err != nil {
108+
return nil, err
109+
}
110+
a = append(a, x)
111+
}
112+
113+
return ast.NewList(a...), nil
114+
}
115+
95116
// Unmarshal parses the JSON-encoded data.
96117
func Unmarshal(b []byte) (ast.Expr, error) {
97118
if !json.Valid(b) {

pkg/encoding/json/pkg.go

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pkg/encoding/json/testdata/gen.txtar

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ t8: {
1515
y: json.Marshal({a: x})
1616
}
1717
t9: json.MarshalStream([{a: 1}, {b: int | *2}])
18+
19+
unmarshalStream: {
20+
t1: json.UnmarshalStream(#"{"a": 1}{"b": 2}"#)
21+
t1: json.UnmarshalStream(#'{"a": 1}{"b": 2}'#)
22+
empty: json.UnmarshalStream('')
23+
empty: json.UnmarshalStream("")
24+
nums: json.UnmarshalStream('1 2')
25+
nums: json.UnmarshalStream("1 2")
26+
}
27+
1828
-- out/json --
1929
Errors:
2030
a: error in call to encoding/json.Validate: invalid value 10 (out of bound <3):
@@ -52,4 +62,13 @@ t9: """
5262
{"b":2}
5363

5464
"""
65+
unmarshalStream: {
66+
t1: [{
67+
a: 1
68+
}, {
69+
b: 2
70+
}]
71+
empty: []
72+
nums: [1, 2]
73+
}
5574

0 commit comments

Comments
 (0)