Home > Software design >  Convert a json to a long data frame in R
Convert a json to a long data frame in R

Time:01-31

I want to convert an json object to a data frame using R.

The data I am working with look like this:

{"A": [123, 234, 345]}
{"B": [1213, 132, 342, 1235]}
{"C": [132, 12]}

I want to convert this something like this:

| Name | Value |
| ---- | ----- |
| A    | 123   |
| A    | 234   |
| A    | 345   |
| B    | 1213  |
| B    | 132   |
| B    | 342   |
| B    | 1235  |
| C    | 132   |
| C    | 12    |

The dataset is quite large (more than 1M entries) so it would be great if the method is scalable.

CodePudding user response:

string <- c("{\"A\": [123, 234, 345]}", "{\"B\": [1213, 132, 342, 1235]}",
            "{\"C\": [132, 12]}")

stack(sapply(string, rjson::fromJSON, USE.NAMES = FALSE))

  values ind
1    123   A
2    234   A
3    345   A
4   1213   B
5    132   B
6    342   B
7   1235   B
8    132   C
9     12   C
  • Related