Git Product home page Git Product logo

bs-json's People

Contributors

adnelson avatar andrewkvalheim avatar ansiwen avatar bobzhang avatar chenglou avatar copy avatar cullophid avatar dependabot[bot] avatar evxn avatar glennsl avatar idkjs avatar imamatory avatar insidersbyte avatar j5bot avatar jchavarri avatar jmuhlich avatar joprice avatar mrmurphy avatar paulshen avatar pewniak747 avatar sroucheray avatar thespyder avatar wokalski avatar yawaramin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

bs-json's Issues

Module build failed

Hi, I installed version 1.3.0 of this package and got this error during a compile time.

Module build failed: Error: We've found a bug for you!
/../node_modules/@glennsl/bs-json/src/Json_decode.ml

  The implementation src/Json_decode.mlast
       does not match the interface src/json_decode.cmi:
       Values do not match:
         val bool : Js.Json.t -> Js.boolean
       is not included in
         val bool : bool decoder
       File "./.../node_modules/@glennsl/bs-json/src/Json_decode.ml", line 18, characters 4-8:
    at <anonymous>claration

Map?

Maybe I'm missing it, but I'm not seeing any map usage to a field in any documentation and would encourage that to be improved. I'm a beginner to Reason / ML.

My json consists of a string url, boolean self, media which is a dict. I don't care what's in media, I just need to know if it's an empty dict (it's fields/types aren't known at runtime anyway). So wanting to decode media as a bool.

My idea:

let decodeJson = json =>
  Json.Decode.{
    url: json |> field("url", string),
    self: json |> field("self", bool),
    media: json |> field("media", map(x=> x == Js.null)), // maybe Js.Dict.empty?
  };
 This has type:
    Json.Decode.decoder(Js.null('a)) => Json.Decode.decoder(bool)
  But somewhere wanted:
    Json.Decode.decoder('b) (defined as Js.Json.t => 'b)

  The incompatible parts:
    Json.Decode.decoder(Js.null('a)) (defined as Js.Json.t => Js.null('a))
    vs
    Js.Json.t (defined as Js.Json.t)

I'm sure I'm not understanding a lot here.

Outdated artifacts in in-source build for Bucklescript 3.

We've been running into runtime errors saying that the bool decoder is undefined using bucklescript 3.0.0 and bs-json 1.3.1, and realized that src/Json_encode.bs.js appears to be an old artifact. It contains references to Js_boolean near the top, as you can see here:

https://unpkg.com/@glennsl/[email protected]/src/Json_encode.bs.js

I don't seem to have problems when I include the package and don't use an in-source build. In that case a new artifact gets dropped into the lib folder, and that new artifact (built using BS 3.0) doesn't use the Json_encode module, but just writes the bool decoder inline as the identity function.

Consider having the compiled JS in the package?

A weird case, but worth the shot:
If one builds his code locally, and deploys this build, then bs-json won't work, as it is not installed with the compiled JS files, but they are generated only when building with it.
That complicates a deployment, as now the deployment will require bucklescript installed in the environment to build everything.

I couldn't find an easy way to deliver the compiled "world" as is into a deployed environment.
Maybe I'm missing something, or maybe missing a current best practice in this community, but I think this use case is fairly wide, just to npm install in the deployed environment, and have everything else precompiled.

Unable to parse integers longer than 10 digits

I've tested this out in a couple examples and it seems throw DecodeError when it is longer than 10 digits. z2 crashes

type x =
  { x : int }

let decodeX json = Json.Decode.{x = field "x" int json}
let t = Js.Json.parseExn "{\"x\":1234567891}" in
let t2 =  Js.Json.parseExn "{\"x\":12345678911}" in
let z = decodeX t in
Js.log z;
let z2 = decodeX t2 in
Js.log z2;

Decoding a function

Is there a way to decode a function as in this example:

{"myfunction": helloWorld()}

You might run a check and see that the value is a function like

let isFunction = a => Js_types.test(Js_types.Function, a);

then need to decode it.

I'm not sure this would be the right way to do it.

Thanks.

The value toJSONUnsafe can't be found in Js.Date

Im getting this error

  13 │ 
  14 │ let date d =
  15 │   d |> Js.Date.toJSONUnsafe
  16 │     |> string

  The value toJSONUnsafe can't be found in Js.Date    at Array.map (<anonymous>)

What could be the problem

Change type of DecodeError

DecodeError right now only accepts a string, and as a result, values need to be stringified in order to be reported. JSON.stringify is used here, and this can lead to confusing results. For example, in
the case of Date objects, JSON.stringify will give you a perfectly reasonable looking ISO-8601 string.

Why discard any information about the value when we can simply add the value directly to the DecodeError constructor as a second argument?

Thanks

Use Belt.List.map instead of StdLib.map

We had an issue with json encoding failing for very large lists due to a stack overflow. We traced it to bs-json and in particular the use of List.map from the stdlib.

Could bs-json be updated to use Belt.List.map instead of List.map?

We can look into making a PR but I first wanted to confirm whether a dependency on Belt would be accepted.

Warning number 44 - this open statement shadows the value identifier float

Hi there!

If I put this code in VSCode:

type record = {
  foo: string,
  timestamp: float,
};

module Decode = {
  let record = json =>
    Json.Decode.{
      foo: field("foo", string, json),
      timestamp: field("timestamp", float, json),
    };
  let all = Json.Decode.array(record);
};

I get this warning message:

Warning number 44
  /home/peter/dev_projects/mub/gui-react/src/error.re 9:5-12:5
  
   7 │ module Decode = {
   8 │   let record = json =>
   9 │     Json.Decode.{
  10 │       foo: field("foo", string, json),
  11 │       timestamp: field("timestamp", float, json),
  12 │     };
  13 │   let all = Json.Decode.array(record);
  14 │ };
  
  this open statement shadows the value identifier float (which is later used)

I get this warning whenever I use float in a situation like this and I couldn't figure out a way to make it disappear. I think the code is correct, no?

I'm using:

  • ReasonML 3.1.0
  • bs-json 1.3.1

Update: I just tested it with the code example from the README with the same result.

Compilation errors : Json.Exn.Error not found

Hello everybody,

I'm new to ReasonReact and i have an errors when I try to run
bsb -make-world
command

I ran npm install before it

I'm on windows

It says that it can't find Js.Exn.Error

$ npm run build:bsb
sentaku-io-front@ build:bsb D:\maws\git\sentaku-io-front
bsb -make-world
Warning: refmt version missing. Please set it explicitly, since we may change the default in the future.

ninja: no work to do.
ninja: no work to do.
[1/1] ←[34mBuilding←[39m ←[2msrc\Json.cmj←[22m
FAILED: src/Json.cmj D:/maws/git/sentaku-io-front/node_modules/@glennsl/bs-json/lib/js/src/Json.bs.js
D:\maws\git\sentaku-io-front\node_modules\bs-platform\lib\bsc.exe -bs-package-name @glennsl/bs-json -bs-package-output commonjs:lib\js\src -bs-assume-has-mli -bs-no-builtin-ppx-ml -bs-no-implicit-include -I src -w -30-40+6+7+27+32..39+44+45+101 -bs-suffix -nostdlib -I "D:\maws\git\sentaku-io-front\node_modules\bs-platform\lib\ocaml" -bs-no-version-header -bs-super-errors -no-alias-deps -color always -o src\Json.cmj -c src\Json.mlast

We've found a bug for you!
D:\maws\git\sentaku-io-front\node_modules@glennsl/bs-json\src\Json.ml 12:5-16

10 Ôöé let parseOrRaise s =
11 Ôöé try Js.Json.parseExn s with
12 Ôöé | Js.Exn.Error e ->
13 Ôöé let message =
14 Ôöé match Js.Exn.message e with

Unbound constructor Js.Exn.Error

ninja: build stopped: subcommand failed.
Failure: D:\maws\git\sentaku-io-front\node_modules\bs-platform\lib\ninja.exe
Location: D:\maws\git\sentaku-io-front\node_modules@glennsl/bs-json\lib\bs
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! sentaku-io-front@ build:bsb: bsb -make-world
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the sentaku-io-front@ build:bsb script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\maws\AppData\Roaming\npm-cache_logs\2018-03-04T18_18_47_590Z-debug.log

Here is a screenshots of my vscode
It shows package.json, bsconfig.js, and the Json.ml file that can't compile

Image of vscode

Thank you in advance 😄

DecodeError vs Js_result.t

Js_result from the BuckleScript library provides Ok and Error. This forces you to catch and handle errors at the type level whereas DecodeError is a runtime error. You can choose to ignore but it will still appear in the runtime. Any reason to prefer a runtime error over a type level one?

How to decode a large tuple?

The repo provides tuple2, tuple3, and tuple4 functions. I have some incoming JSON that includes stuff like this: ["Q",-223.5,473,-221.5,471.5]. I made a tuple5 function, solving my problem, but, generally, if there are incoming tuples that are long and have multiple types within them (so you can't use list or array), how might one decode them?

Thanks much!

Example code spit out a warning

For clarity, the example code on the README.md page contains:

type point = {
  x: float,
  y: float
};

module Decode = {
  let point = json =>
    Json.Decode.{
      x: json |> field("x", float),
      y: json |> field("y", float)
    };
};

When trying to compile this, I get:

  Warning number 44
  /path/to/Test.re 9:5-12:5
  
   7 │ module Decode = {
   8 │   let point = json =>
   9 │     Json.Decode.{
  10 │       x: json |> field("x", float),
  11 │       y: json |> field("y", float)
  12 │     };
  13 │ };
  14 │ 
  
  this open statement shadows the value identifier float (which is later used)

I get this behavior whenever attempting to parse a float field.

Can't use this project

Hi Glenn,

I am sorry to open this issue, it is more an issue with how BuckleScript works.
After installing your project using npm install --save @glennsl/bs-json and then added it to bsconfig.json under bs-dependencies I get this error when running bsb -make-world in the root of my project:

👉  bsb -make-world
ninja: no work to do.
Duplicated package: bs-platform /Users/montogeek/Infinite/Lov/online/node_modules/bs-platform (chosen) vs /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-platform in /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json
[1/3] Building src/Json_encode.cmj
FAILED: src/Json_encode.cmj /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/src/Json_encode.bs.js
/Users/montogeek/.nvm/versions/node/v10.0.0/lib/node_modules/bs-platform/lib/bsc.exe -bs-package-name @glennsl/bs-json  -bs-package-output commonjs:src -bs-assume-has-mli -bs-no-builtin-ppx-ml -bs-no-implicit-include   -I src  -w -30-40+6+7+27+32..39+44+45+101 -bs-suffix -nostdlib -I '/Users/montogeek/Infinite/Lov/online/node_modules/bs-platform/lib/ocaml' -bs-no-version-header -bs-super-errors -no-alias-deps -color always -o src/Json_encode.cmj -c  src/Json_encode.mlast
Fatal error: exception Failure("File \"external_ffi_types.ml\", line 261, characters 13-20Compiler version mismatch. The project might have been built with one version of BuckleScript, and then with another. Please wipe the artifacts and do a clean build.")
[2/3] Building src/Json_decode.cmj
FAILED: src/Json_decode.cmj /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/src/Json_decode.bs.js
/Users/montogeek/.nvm/versions/node/v10.0.0/lib/node_modules/bs-platform/lib/bsc.exe -bs-package-name @glennsl/bs-json  -bs-package-output commonjs:src -bs-assume-has-mli -bs-no-builtin-ppx-ml -bs-no-implicit-include   -I src  -w -30-40+6+7+27+32..39+44+45+101 -bs-suffix -nostdlib -I '/Users/montogeek/Infinite/Lov/online/node_modules/bs-platform/lib/ocaml' -bs-no-version-header -bs-super-errors -no-alias-deps -color always -o src/Json_decode.cmj -c  src/Json_decode.mlast
Fatal error: exception Failure("File \"external_ffi_types.ml\", line 261, characters 13-20Compiler version mismatch. The project might have been built with one version of BuckleScript, and then with another. Please wipe the artifacts and do a clean build.")
ninja: build stopped: subcommand failed.
Failure: /Users/montogeek/.nvm/versions/node/v10.0.0/lib/node_modules/bs-platform/lib/ninja.exe
 Location: /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/lib/bs

I already tried installing dependencies in your project then run bsb -make-world but get the same error:

montogeek ~/Infinite/Lov/online/node_modules/@glennsl/bs-json [01:12 PM]→ 😀  (master)
👉  bsb -make-world
[1/1] Building src/jest.cmj
FAILED: src/jest.cmj /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-jest/src/jest.js
/Users/montogeek/.nvm/versions/node/v10.0.0/lib/node_modules/bs-platform/lib/bsc.exe -bs-package-name bs-jest  -bs-package-output commonjs:src -bs-assume-has-mli -bs-no-builtin-ppx-ml -bs-no-implicit-include   -I src  -w -30-40+6+7+27+32..39+44+45+101 -nostdlib -I '/Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-platform/lib/ocaml' -bs-no-version-header -bs-super-errors -no-alias-deps -color always -o src/jest.cmj -c  src/jest.mlast

  Warning number 3
  /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-jest/src/jest.ml 86:66-86

  84 ┆ | Equal `Just (a, b) -> (expect a) ## toEqual b
  85 ┆ | Equal `Not (a, b) -> (expect a) ## not ## toEqual b
  86 ┆ | FloatCloseTo `Just (a, b, p) -> (expect a) ## toBeCloseTo b (Js.Unde
       fined.from_opt p)
  87 ┆ | FloatCloseTo `Not (a, b, p) -> (expect a) ## not ## toBeCloseTo b (J
       s.Undefined.from_opt p)
  88 ┆ | GreaterThan `Just (a, b) -> (expect a) ## toBeGreaterThan b

  deprecated: Js.Undefined.from_opt
Use fromOption instead

  Warning number 3
  /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-jest/src/jest.ml 87:72-92

  85 ┆ | Equal `Not (a, b) -> (expect a) ## not ## toEqual b
  86 ┆ | FloatCloseTo `Just (a, b, p) -> (expect a) ## toBeCloseTo b (Js.Unde
       fined.from_opt p)
  87 ┆ | FloatCloseTo `Not (a, b, p) -> (expect a) ## not ## toBeCloseTo b (J
       s.Undefined.from_opt p)
  88 ┆ | GreaterThan `Just (a, b) -> (expect a) ## toBeGreaterThan b
  89 ┆ | GreaterThan `Not (a, b) -> (expect a) ## not ## toBeGreaterThan b

  deprecated: Js.Undefined.from_opt
Use fromOption instead
Fatal error: exception Failure("File \"external_ffi_types.ml\", line 261, characters 13-20Compiler version mismatch. The project might have been built with one version of BuckleScript, and then with another. Please wipe the artifacts and do a clean build.")
ninja: build stopped: subcommand failed.
Failure: /Users/montogeek/.nvm/versions/node/v10.0.0/lib/node_modules/bs-platform/lib/ninja.exe
 Location: /Users/montogeek/Infinite/Lov/online/node_modules/@glennsl/bs-json/node_modules/bs-jest/lib/bs

BuckleScript isn't really been helpful (rescript-lang/rescript-compiler#2347).

Additional info:

montogeek ~/Infinite/Lov/online [01:17 PM]→ 😀  (master)
👉  bsb -version
3.1.1
  "devDependencies": {
    "bs-platform": "3.1.3",
    "bs-fetch": "0.3.0"
  }

Thanks for help a new comer.

Upgrade path for Deprecated Boolean Codec

What's the upgrade path for this? For encode I suppose Obj.magic will do the trick (although it would be less idiomatic and intuitive IMHO) but for decode, what do we do?

Also, what was e277c2b about? Was that to accommodate people who haven't updated bs-platform like Issue #31 ? Will there be a new release soon for people have upgraded?

I'm trying pretty hard to get rid of all the annoying compiler warnings :)

Encode Integer into an Array of Integer

Hi, I have small problem when using bs-json. In some cases, I want to convert an integer into an array of integer e.g [1] or [0]. But I am still confusing how to do it with Json.Encode for sending through request payload.

I have read the examples of

let _ =
  [| "foo"; "bar" |]
  |> Json.Encode.stringArray
  |> Json.stringify
  |> Js.log

But it's array of string.

Thank you very much.

Handling fields that may not exist

If a field is undefined it doesn't serialize to a keyed field in Json. It just won't be there.

So in my case if I have a field that may or may not exist at all (not simply be on the object but null)

Here's a short example:

let decodeTodos =
  Json.Decode.array(item =>
    Json.Decode.{
      notes: item |> field("notes", optional(string)),
    }
  );

let decoded = decodeTodos(Js.Json.parseExn("[{}]"));

This leads to the error Expected field 'notes'

Is there a way to deal with these fields?

link to example showcase

My current work around is

notes:
        item
        |> Json.Decode.withDefault(None, field("notes", optional(string))),

optionalField Decoder

When parsing user input it's important to be able to give good error messages. For example in a http PATCH request, the date_of_birth field might only accept a UTC conformant string when the field is present. If a user passes in a number, we need to return with a 400 BAD REQUEST.

When using the optional decoder in combination with the field decoder, if the field exists but the inner decoder fails, the final result will be None.

In the previous example { dateOfBirth: optional(field("date_of_birth", utcString)) } when fed with the payload { "date_of_birth": 1234 } would simply be { dateOfBirth: None }. The actual semantics that needed to be captured in this example was:

  • { } becomes { dateOfBirth: None }
  • { "date_of_birth": "Wed, 14 Feb 2018 10:22:19 GMT" } becomes { dateOfBirth: Some("Wed, 14 Feb 2018 10:22:19 GMT")
  • { "date_of_birth": 123457 } becomes Json.Decoder.DecoderError("Expected a UTC string, got a number")

An optionalField decoder (or a decoder with a similar name) would solve this problem by returning None if the field is undefined, else would bubble up the error from inner decoder.

File names don't resolve on OS X

After installing the library, I was getting this error when trying to use it:

Module not found: `/Users/will/Code/reason/autocomplete/node_modules/bs-json/lib/js/src/json_decode.js` does not match the corresponding path on disk `Json_decode.js`.

It looks like a recent update to BuckleScript changed the way that the compiled js files are named, switching to beginning with lowercase. The require statements generated also expect the file names to begin with lowercase.

Running bsb -clean-world fixed the issue, but the checked-in js/ folder should probably be corrected to avoid issues with people installing for the first time.

How to encode option to undefined?

How to encode option into undefined which will be removed from JSON by JSON.stringify?

graphql_ppx generates decoders and encoders for GraphQL queries and in GraphQL if the input argument is optional and not present in the payload to the server it shouldn't be present in the JSON. Currently, we encode it as null which breaks some requests because there is no way to encode is as undefined or nonexistent.

Original issues:

Convert to rescript

Hi, would there be interest in a PR converting the repo to rescript 9.1? If so, are there any concerns or preferences around it (such as versions to support in the build matrix)?

Functions mentioned don't exist

In the Json.mli file there is a comment (below) that mentions the reifyType and test functions. I don't think these functions exist in the repo.

Decoding is a more complex process, due to the highly dynamic nature of JSON
data structures. There are several ways to decode a JSON data structure,
depending on your needs. This module provides two fairly low level methods
of decoding, the assertive, more convenient but also more rigid {! Decode}
module and the more flexible but cumbersome {! reifyType} and {! test} functions.
The third way is to use a opinionated third-party APIs that makes other tradeoffs.

Support for int64

I tried with a custom decoder function, but it did not work as it is passed an already parsed number as double, so values >2^53 are rounded.

Js.Date.toJSON warning

I got the following message when using this library:

  Warning number 3
  /path/to/node_modules/@glennsl/bs-json/src/Json_encode.ml 15:8-21
  
  13 │ 
  14 │ let date d =
  15 │   d |> Js.Date.toJSON
  16 │     |> string
  17 │ 
  
  deprecated: Js.Date.toJSON
This method is unsafe. It will be changed to return option in a future release. Please use toJSONUnsafe instead.

Package fails to build

  We've found a bug for you!
  /Users/nick/Documents/GitHub/reason-react-newer/node_modules/@glennsl/bs-json/src/Json_encode.ml 15:8-27
  
  13 │ 
  14 │ let date d =
  15 │   d |> Js.Date.toJSONUnsafe
  16 │     |> string
  17 │ 
  
  The value toJSONUnsafe can't be found in Js.Date

Can't find list.js

I install bs-json with npm --save and added it as a dependency to bsconfig.json.

Attempting to use it, I get the following error message in browser console:

Error: Cannot find module 'bs-platform/lib/js/list.js' from 'bs-json/lib/js/src/json_decode.js'

The file is there remotely, but shouldn't it be compiled into the code somehow? I must be missing a configuration step?

I am using brunch, and I can successfully use the bs-fetch module that's also in this organization.

Fails to compile, complaining about `Js.boolean`

I just installed [email protected] and I'm getting this error when trying to start my server:

[0/6] Building src/Json_decode.cmi[0/6] Building src/Json_encode.cmi[1/6] Building src/Json_decode.cmi

  We've found a bug for you!
  /Users/allen/workspace/reason/tracker/frontend/node_modules/bs-json/src/Json_decode.mli 18:15-24
  
  16 │ exception DecodeError of string
  17 │ 
  18 │ val boolean : Js.boolean decoder
  19 │ (** Decodes a JSON value into a [Js.boolean]
  20 │     
  
  This type constructor's parameter, `Js.boolean`, can't be found. Is it a typo?
  
[2/6] Building src/Json_encode.cmi

  We've found a bug for you!
  /Users/allen/workspace/reason/tracker/frontend/node_modules/bs-json/src/Json_encode.mli 18:20-29
  
  16 │ (** [int n] makes a JSON number of the [int] [n] *)
  17 │ 
  18 │ external boolean : Js.boolean -> Js.Json.t = "%identity" 
  19 │ (** [boolean b] makes a JSON boolean of the [Js.boolean] [b] *)
  20 │ 
  
  This type constructor's parameter, `Js.boolean`, can't be found. Is it a typo?
  
Failure: /Users/allen/workspace/reason/tracker/frontend/node_modules/bs-platform/lib/ninja.exe 
 Location: /Users/allen/workspace/reason/tracker/frontend/node_modules/bs-json/lib/bs    at Array.map (<anonymous>)

This seems related to #30. I'm on version 4.0.8 of bs-platform.

Thoughts on a "runParse" function?

It would seem like a common use case to both parse and convert in a single step:

let runParse: (Js.Json.t => 'a, string) => option('a) = (decoder, json) =>
  Json.parse(json) |. Belt.Option.map(decoder);

with the idea that then there's never any raw Js.Json.t value floating around. We've gone directly from a JSON blob, to (optionally) our domain value. In the docs there's the example:

let line = data |> Json.parseOrRaise
                |> Decode.line;

which could have the equivalent:

let line = Json.runParseOrRaise(Decode.line, data);

Just a thought. Thanks!

Encode list

missing the option to encode a list,
currently im doing let list encoder xs => xs |> List.map encoder |> Array.of_list |> Json.Encode.array.
It works fine, but support in the lib would be great.

Sorry for not doing a PR, but i haven't quite figured out how the lib works

Reopen Issue #42?

I couldn't find a button to re-open issue #42 to bring it to your attention :)

Please let me know your thoughts!

Safe Decode?

First of all, thank you for the great decoding lib!

I'm new to Reason. I'm struggling with catching the exceptions that occur while decoding JSON. I have a simple decoder

let decodeState = (json: Js.Json.t): state =>
  Json.Decode.{
    ctr: json |> field("ctr", int)
  };

and I use like this:

let restore = (): state => {
  switch Dom.Storage.(localStorage |> getItem("test-data")) {
    | None => init
    | Some(stateStr) => {
      try (decodeState(Json.parseOrRaise(stateStr))) {
        | Json.ParseError(e) => {
          Js.log2("2. Error:", e);
          init
        }
      };
    }
  };
};

I altered the entry in my localStorage so that I don't have a string there instead of a number. The program crashes with Json_decode.DecodeError,5,Expected number, got "not_a_number" and I can't catch the exception.

How to I help it?

This open statement shadows the value identifier float

Hej, I'm trying to create a simple working example based on the examples. It is working but I get a warning. Here my code

type random = {
    number: float
};

module Decode = {
    let random = (json) =>
        Json.Decode.{
            number: json |> field("number", float)
        };
};

let fetchRandomNumber = (callback) =>
    Js.Promise.(
        Fetch.fetch(apiBaseUrl)
        |> then_(Fetch.Response.json)
        |> then_((payload) => {
            callback(Decode.random(payload));
            resolve(None)
        })
    );

I get this warning everytime

module Decode = {
  let random = (json) =>
    Json.Decode.{
      number: json |> field("number", float)
    };
};
this open statement shadows the value identifier float (which is later used)

Can it be related to the bs-json library ?

Number.isInteger() throws error in IE

Number.isInteger() (https://github.com/reasonml-community/bs-json/blob/master/src/Json_decode.ml#L1) is not supported in IE (https://caniuse.com/#search=isInteger). Don't know what is the best way to solve this. One would be providing polyfill, that's not very elegant but was the workaround we did in our project to bypass this error:

[%bs.raw
  {|Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
}|}];

Include `parseAsResult` (or something)

I was wondering if you would consider adding a function to parse but return Belt.Result.t.

The parse method already included that returns Option is nice because it allows for a more graceful failure, it looses the error message about why the JSON was invalid. The Result type doesn't have this limitation since you can specify an failure type. Additionally, it allows for better compile-time bug catching compared to parseOrRaise.

Implementation would be relative simple, something like this in src/Json.ml:

module R = Belt.result;

let parseAsResult s =
  try R.Ok (Js.Json.parseExn s) with
  | Js.Exn.Error e ->
    let message =
      match Js.Exn.message e with
      | Some m  -> m
      | None    -> "Unknown error"
in (R.Error message)

(The syntax might be off, I'm not as familiar with ocaml syntax)

Currently the Result type (and the entire Belt std lib) is in beta, so I wouldn't think this should happen until the API is stable.

How to decode array?

It looks like all the examples are JSON objects. I want to decode an array of objects and create a map out of it, but it's not clear how to accomplish this.

Also, confused why some examples have .ml extension. I think they are using an old syntax of Reason?

Issue using bs-json with bs-tea

Using the instructions in the README I get following error when trying to use bs-json (using OCaml Syntax).

The module or file Json.Decode can't be found.
  - If it's a third-party dependency:
    - Did you list it in bsconfig.json?
    - Did you run `bsb` instead of `bsb -make-world`
      (latter builds third-parties)?
  - Did you include the file's directory in bsconfig.json?
  
  Hint: Did you mean Decoder?

I couldn't pinpoint the exact problem, but I assume there is a naming conflict when bs-json is used in conjunction with BuckleScript-Tea. Is this a known issue? If so, what can I do about it?

The problem is I opened Tea globally, it's a dumb error. The error messages of bsb are not helpful at all, if I had the type signature instead of the error above I would have catched it earlier. This can be closed. Sorry for the interruption.

Request Dual License MIT

I'm considering using bs-json for a project but can't include software with LGPL or GPL licenses.

I notice that it began with an MIT license and was re-licensed LGPL after 1.2.0.
Would you be willing to license the package dual license MIT/LGPL?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.