Skip to content

Commit

Permalink
ppx: fix float_of_json to handle `Int
Browse files Browse the repository at this point in the history
In browser JSON.stringify(1.0) will yield 1 which will be parsed as
(`Int 1) by Yojson and finally used before this commit
Yojson.Basic.Util.to_float will fail on it as it expectes (`Float n).

So this commit changes float_of_json to be Yojson.Basic.Util.to_number
which handles both (`Float n) and (`Int n).
  • Loading branch information
andreypopp committed Oct 2, 2024
1 parent d25729f commit 8e617a6
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ppx/native/ppx_deriving_json_runtime.ml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module Of_json = struct
let string_of_json = Yojson.Basic.Util.to_string
let bool_of_json = Yojson.Basic.Util.to_bool
let int_of_json = Yojson.Basic.Util.to_int
let float_of_json = Yojson.Basic.Util.to_float
let float_of_json = Yojson.Basic.Util.to_number

let unit_of_json = function
| `Null -> ()
Expand Down
4 changes: 4 additions & 0 deletions ppx/test/example.ml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
type user = int [@@deriving json]
type floaty = float [@@deriving json]
type 'a param = 'a [@@deriving json]
type opt = string option [@@deriving json]
type res = (int, string) result [@@deriving json]
Expand All @@ -23,6 +24,9 @@ module Cases = struct
type of_json = C : string * (json -> 'a) * ('a -> json) * 'a -> of_json
let of_json_cases = [
C ({|1|}, user_of_json, user_to_json, 1);
C ({|1.1|}, floaty_of_json, floaty_to_json, 1.1);
C ({|1.0|}, floaty_of_json, floaty_to_json, 1.0);
C ({|42|}, floaty_of_json, floaty_to_json, 42.0);
C ({|"OK"|}, (param_of_json string_of_json), (param_to_json string_to_json), "OK");
C ({|"some"|}, opt_of_json, opt_to_json, (Some "some"));
C ({|["Ok", 1]|}, res_of_json, res_to_json, Ok 1);
Expand Down
6 changes: 6 additions & 0 deletions ppx/test/ppx_deriving_json_js.e2e.t
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
$ node ./_build/default/output/main.js
JSON DATA: 1
JSON REPRINT: 1
JSON DATA: 1.1
JSON REPRINT: 1.1
JSON DATA: 1.0
JSON REPRINT: 1
JSON DATA: 42
JSON REPRINT: 42
JSON DATA: "OK"
JSON REPRINT: "OK"
JSON DATA: "some"
Expand Down
6 changes: 6 additions & 0 deletions ppx/test/ppx_deriving_json_native.e2e.t
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
$ dune exec ./main.exe
JSON DATA: 1
JSON REPRINT: 1
JSON DATA: 1.1
JSON REPRINT: 1.1
JSON DATA: 1.0
JSON REPRINT: 1.0
JSON DATA: 42
JSON REPRINT: 42.0
JSON DATA: "OK"
JSON REPRINT: "OK"
JSON DATA: "some"
Expand Down

0 comments on commit 8e617a6

Please sign in to comment.