Skip to content

Commit 1c81e23

Browse files
authored
Fix json5 downgrade with dangling comma (#21)
1 parent b42051d commit 1c81e23

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

json5/json5.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,17 @@ func Downgrade(data []byte) ([]byte, error) {
3232
return nil, err
3333
}
3434

35-
return json.Marshal(v)
35+
if d, err := json.Marshal(v); err == nil {
36+
return d, nil
37+
}
38+
39+
// Fallback decoding for cases like a dangling comma.
40+
var i interface{}
41+
if err := Unmarshal(data, &i); err != nil {
42+
return nil, err
43+
}
44+
45+
return json.Marshal(i)
3646
}
3747

3848
// Unmarshal parses the JSON5-encoded data and stores the result

json5/json5_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ func TestDowngrade(t *testing.T) {
5656
assert.Equal(t, `{"xyz":123,"abc":987}`, string(j))
5757
}
5858

59+
func TestDowngrade2(t *testing.T) {
60+
dd, err := json5.Downgrade([]byte(`{
61+
"values": {
62+
"app_token::$appToken::web_tracking_enabled": "1",
63+
"app_token::$appToken::web_redirect_base_url": "http://redirect.com",
64+
}
65+
}`))
66+
67+
require.NoError(t, err)
68+
assert.Equal(t, `{"values":{"app_token::$appToken::web_redirect_base_url":"http://redirect.com","app_token::$appToken::web_tracking_enabled":"1"}}`, string(dd))
69+
}
70+
5971
func TestDowngrade_array(t *testing.T) {
6072
j5 := ` [{
6173
// XYZ.

0 commit comments

Comments
 (0)