moonbitlang / core

MoonBit's Core library
https://moonbitlang.com/
Apache License 2.0
628 stars 78 forks source link

Json::stringify handles forward slashes in Strings unusually #893

Closed gmlewis closed 2 months ago

gmlewis commented 2 months ago

In JavaScript, if I write this:

const a = "https://example.com"
console.log(a)
// => 'https://example.com'
console.log(JSON.stringify(a))
// => '"https://example.com"'

However, in MoonBit, if I write this:

test "Json::stringify works on strings" {
  let url = "https://example.com"
  let got = url.to_json().stringify()
  let want =
    #|"https://example.com"
  assert_eq!(got, want)
}

I get this:

test gmlewis/moonbit-pdk/pdk/http/http.mbt::Json::stringify works on strings failed: FAILED: /Users/glenn/.moonup/toolchains/latest/lib/core/builtin/assert.mbt:23:5-23:43 FAILED: /Users/glenn/src/github.com/gmlewis/moonbit-pdk/pdk/http/http.mbt:73:3-73:24 `"https:\/\/example.com" == "https://example.com"`
Total tests: 1, passed: 0, failed: 1.
guuzaa commented 2 months ago

The json package will add \ before escapes, including ", \, and /, when stringifying a json object. https://github.com/moonbitlang/core/blob/34096f4e37269777274b3ed6a2eed499890ae030/json/json.mbt#L146 There are some discussion on stack overflow. I think it’s just a matter of choosing.

yj-qin commented 2 months ago

According to the ECMA specification, the forward slash can be escaped. But some implementations choose not to escape it or provide an option.

https://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped

Maybe we can align with JavaScript's behavior.

bobzhang commented 2 months ago

following other language's conventions, we provide a flag so you can set it, e.g,

xx.stringify(escape_flash=false)
gmlewis commented 2 months ago

following other language's conventions, we provide a flag so you can set it, e.g,

xx.stringify(escape_flash=false)

Excellent... Thank you! Additionally, you might want to add some flags to support pretty-printing with indentation.