Skip to content

Commit

Permalink
Fix json5 downgrade with dangling comma (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Apr 27, 2023
1 parent b42051d commit 1c81e23
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
12 changes: 11 additions & 1 deletion json5/json5.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,17 @@ func Downgrade(data []byte) ([]byte, error) {
return nil, err
}

return json.Marshal(v)
if d, err := json.Marshal(v); err == nil {
return d, nil
}

// Fallback decoding for cases like a dangling comma.
var i interface{}
if err := Unmarshal(data, &i); err != nil {
return nil, err
}

return json.Marshal(i)
}

// Unmarshal parses the JSON5-encoded data and stores the result
Expand Down
12 changes: 12 additions & 0 deletions json5/json5_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ func TestDowngrade(t *testing.T) {
assert.Equal(t, `{"xyz":123,"abc":987}`, string(j))
}

func TestDowngrade2(t *testing.T) {
dd, err := json5.Downgrade([]byte(`{
"values": {
"app_token::$appToken::web_tracking_enabled": "1",
"app_token::$appToken::web_redirect_base_url": "http://redirect.com",
}
}`))

require.NoError(t, err)
assert.Equal(t, `{"values":{"app_token::$appToken::web_redirect_base_url":"http://redirect.com","app_token::$appToken::web_tracking_enabled":"1"}}`, string(dd))
}

func TestDowngrade_array(t *testing.T) {
j5 := ` [{
// XYZ.
Expand Down

0 comments on commit 1c81e23

Please sign in to comment.