Decoding several JSON fields into a specific data structure

#1

I’ve a large JSON with many objects similar to these two:

  {
    "Agent1": {
      "aliases": [
        "agent_1",
        "agent1"
        ],
      "extras": [
        "a",
        "b",
        "c"
      ]
    },
    "Agent2": {
      "aliases": [
        "agent_2",
        "agent2",
        "original"
        ],
      "extras": [
        "d",
        "e",
        "f"
      ]
    }
  }

and I’m looking to construct a data structure adequate to have a lookup function which receives one of those extra and it will return the list of aliases corresponding to that particular extra. For example, the JSON above would be decoded into a dictionary like this:

{
  a => ["agent_1", "agent1"],
  b => ["agent_1", "agent1"],
  c => ["agent_1", "agent1"],
  d => ["agent_2", "agent2", "original"],
  f => ["agent_2", "agent2", "original"],
  g => ["agent_2", "agent2", "original"],
}

so that a function like getAliases "f" == ["agent_2", "agent2", "original"] would be possible.

I have some experience decoding JSON in Elm, but I’ve got no idea on how to achieve this since it seems like it would require some kind of folding function to accumulate over all objects in the JSON? I’m also not completely sure what would be the best data structure to lookup the data. Any help is appreciated :slight_smile:

Thanks!

#2

I took a stab at this: https://ellie-app.com/5ndvNfbv8Qba1

Assumptions:

  • each “extra” appears for at most one set of aliases
  • the actual “name” of the object in which things appear doesn’t matter

The basic strategy I used is to

  1. decode each agent’s extras and aliases into a Dict String (List String), mapping each “extra” to all the aliases
  2. Union all those dicts together

The result is a Dict String (List String) again, which can then be used as a lookup table.

If my first assumption doesn’t hold, and assuming that aliases are unique, you could use Dict.merge Dict.insert (\key left right acc -> Dict.insert key (left ++ right) acc) Dict.insert instead of Dict.union to join the aliases together.

closed #3

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.