From 1c81e23eb9472e1103eeeaf850bf423ce297d6df Mon Sep 17 00:00:00 2001 From: Viacheslav Poturaev Date: Thu, 27 Apr 2023 17:22:47 +0200 Subject: [PATCH] Fix json5 downgrade with dangling comma (#21) --- json5/json5.go | 12 +++++++++++- json5/json5_test.go | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/json5/json5.go b/json5/json5.go index a01a42c..cc32ccf 100644 --- a/json5/json5.go +++ b/json5/json5.go @@ -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 diff --git a/json5/json5_test.go b/json5/json5_test.go index 6badfbd..d0071a7 100644 --- a/json5/json5_test.go +++ b/json5/json5_test.go @@ -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.