Home > Back-end >  How to remove a member from a JSON object using YoJson?
How to remove a member from a JSON object using YoJson?

Time:11-19

I am trying to functionally remove a member of a Yojson.Safe.t.

For example:

{
  id: 123,
  name: "bob",
  roles: ["admin", "user"]
}

If I was to remove the id member, the result would look like:

{
  name: "bob",
  roles: ["admin", "user"]
}

I originally thought that something like this would do it:

Yojson.Safe.Util.to_assoc json 
|> List.filter (fun (t, _) -> t != "id")
|> fun t -> `Assoc t

But for some reason it keeps the member anyways. How can I remove a member from a Yojson.Safe.t?

CodePudding user response:

Don't use != to compare strings! Use <>:

# "abc" != "abc";;
- : bool = true
# "abc" <> "abc";;
- : bool = false

The != operator is "physical inequality", i.e., the inverse of the == operator. These are not for general use, especially not on immutable values.

The workhorse operators for comparison are = and <>.

  • Related