Is it possible to transform json key into its own data field in vega-lite?

Viewed 121

I'm trying to build a chart from live json data but the format has the date data as the key for other nested data, the essential structure is:

{
"Meta": {
    "Frequency": "Monthly",
    "Time zone": "EST"
},
"Monthly data": {
    "2022-01-01": {
        "valueA": "13.44",
        "valueB": "97.68"
    },
    "2021-12-01": {
        "valueA": "11.39",
        "valueB": "99.81"
    },
    "2021-11-01": {
        "valueA": "12.31",
        "valueB: "93.56"
    },
    "2022-10-01": {
        "valueA": "15.42",
        "valueB": "98.54"
    }
}}

I'm trying to get into a format where i can encode the date on the x-axis, but can't as there is no column name/key and it isn't an array so cannot flatten. Then would be looking to encode any normal nested field (eg valueA) on the y-axis, but can't find any documentation or examples on this specific case. I don't need any information in the metadata part so can be ignored.

The only similar comment on this I've found is https://github.com/vega/vega/issues/1360, I can get this to work as a test but typing out each monthly date to map of course removes the benefit of live data and wouldn't allow high-frequency data.

Is there a way for this to be mapped automatically?

1 Answers

No, I don't believe this is currently possible. You could potentially do it with the flatten transform if there were a vega expression for extracting keys from an object, but support for this has not yet been added to vega expressions (see https://github.com/vega/vega/issues/3207 for a similar request).

Unfortunately, I believe the best you can do currently is use the fold transform while specifying the keys explicitly. For example:

{
  "data": {
    "values": {
      "2022-01-01": {"valueA": "13.44", "valueB": "97.68"},
      "2021-12-01": {"valueA": "11.39", "valueB": "99.81"},
      "2021-11-01": {"valueA": "12.31", "valueB": "93.56"},
      "2022-10-01": {"valueA": "15.42", "valueB": "98.54"}
    }
  },
  "transform": [
    {
      "fold": ["2021-11-01", "2021-12-01", "2022-01-01", "2022-10-01"],
      "as": ["date", "value"]
    },
    {"calculate": "datum.value.valueA", "as": "valueA"},
    {"calculate": "datum.value.valueB", "as": "valueB"}
  ],
  "mark": "bar",
  "encoding": {
    "y": {"field": "date"},
    "x": {"field": "valueA"},
    "x2": {"field": "valueB"}
  }
}

enter image description here

Related