Home > Software engineering >  How to fix json code to split in a table using dplyr
How to fix json code to split in a table using dplyr

Time:02-03

I'm trying to split this json code into an easier way to parse my data, I have tried to use jsonlite with fromJSON() but doesn't work.

Data

{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}
library(jsonlite)

jsonStr <- '{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}'

t = fromJSON(jsonStr)

> t
$PROB
[1] 0.06697738

$Y
[1] -3.221017

$x
[1] 933

expected output

        PROB         Y   x
1 0.06697738 -3.221017 933

CodePudding user response:

You can create a tibble (data frame) from the parsed JSON data:

library(jsonlite)

jsonStr <- '{
    "PROB": 0.066977381909206,
    "Y": -3.221016563928024,
    "x": 933
}'

t <- fromJSON(jsonStr)

# create an empty data frame to store the result
df <- data.frame()

# loop through each variable in the list
for (name in names(t)) {
  df[name] <- t[[name]]
}

# assign row names
rownames(df) <- "1"

df

Result:

# A tibble: 1 × 3
    PROB     Y     x
   <dbl> <dbl> <int>
1 0.0670 -3.22   933
  • Related