Revisão | 86376ef1ac7bd26fca38a09f5a43a387cf539066 (tree) |
---|---|
Hora | 2025-01-18 08:33:39 |
Autor | Lorenzo Isella <lorenzo.isella@gmai...> |
Commiter | Lorenzo Isella |
A script with some recursive functions to change a generic nested json file into a tibble.
@@ -0,0 +1,57 @@ | ||
1 | +library(jsonlite) | |
2 | +library(tibble) | |
3 | + | |
4 | +# Flatten JSON function (from earlier) | |
5 | +flatten_json <- function(data, parent_key = "", sep = ".") { | |
6 | + result <- list() | |
7 | + | |
8 | + if (is.list(data)) { | |
9 | + for (key in names(data)) { | |
10 | + new_key <- if (parent_key == "") key else paste0(parent_key, sep, key) | |
11 | + result <- c(result, flatten_json(data[[key]], new_key, sep)) | |
12 | + } | |
13 | + } else if (is.atomic(data) && length(data) > 1) { | |
14 | + for (index in seq_along(data)) { | |
15 | + new_key <- if (parent_key == "") as.character(index - 1) else paste0(parent_key, sep, index - 1) | |
16 | + result[[new_key]] <- data[index] | |
17 | + } | |
18 | + } else { | |
19 | + result[[parent_key]] <- data | |
20 | + } | |
21 | + | |
22 | + return(result) | |
23 | +} | |
24 | + | |
25 | +# Function to convert flattened JSON to a tibble | |
26 | +json_to_tibble <- function(flattened_json) { | |
27 | + # Create a tibble with two columns: key and value | |
28 | + tibble( | |
29 | + key = names(flattened_json), | |
30 | + value = unlist(flattened_json, use.names = FALSE) | |
31 | + ) | |
32 | +} | |
33 | + | |
34 | +# Example Usage | |
35 | +## json_data <- '{ | |
36 | +## "a": 1, | |
37 | +## "b": {"c": 2, "d": {"e": 3}}, | |
38 | +## "f": [4, 5, {"g": 6}], | |
39 | +## "h": "text" | |
40 | +## }' | |
41 | + | |
42 | +## details <- fromJSON(fname) | |
43 | + | |
44 | +## json_data <- fromJSON("../output/dataset.json") | |
45 | + | |
46 | + | |
47 | +# Parse JSON | |
48 | +data <- fromJSON("../output/dataset.json", simplifyVector = FALSE) | |
49 | + | |
50 | +# Flatten the JSON | |
51 | +flattened <- flatten_json(data) | |
52 | + | |
53 | +# Convert to tibble | |
54 | +tibble_result <- json_to_tibble(flattened) | |
55 | + | |
56 | +# Print the result | |
57 | +print(tibble_result) |