1

I'm been working with JSON response from API, and have been able to return the data in a format that looks very JSON (which is good) and not struggling to get into DataFrame. Here is the code:

message(typeof((results_response)))
# character
message(length((results_response)))
# 1 

message(results_response)
# {"central_time":{"0":"2020-04-06 15:47:00","1":"2020-04-06 15:47:15"},"Va_V":{"0":286.032,"1":286.207}}

The goal would not hard coding the keys, because there could be other responses when different keys. thank you!

jKraut
  • 2,325
  • 6
  • 35
  • 48
  • @akrun yes. When i do that is causing this: `0` = "2020-04-09 15:47:00", `1` = "2020-04-09 15:47:15")list(`0` = 286.032 `1` = 286.207) – jKraut May 16 '20 at 21:39

2 Answers2

0

May be this helps

library(jsonlite)
library(purrr)
library(dplyr)
fromJSON(results_response) %>%
     transpose %>% 
     bind_rows
 # A tibble: 2 x 2
 #  central_time         Va_V
 #* <chr>               <dbl>
#1 2020-04-06 15:47:00  286.
#2 2020-04-06 15:47:15  286.

data

results_response <- "{\"central_time\":{\"0\":\"2020-04-06 15:47:00\",\"1\":\"2020-04-06 15:47:15\"},\"Va_V\":{\"0\":286.032,\"1\":286.207}}"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

The following should work

library(jsonlite)

# Your JSON charachter vector.
json <- 

df <- as.data.frame(fromJSON(json))

See jsonlite Documentation and the answer to How can I convert Json to data frame in R.

I hope this helps!

EDITED The following code did run without errors.

library(jsonlite)

json <- as.character(
  '{"central_time":{"0":"2020-04-06 15:47:00","1":"2020-04-06 15:47:15"}, "Va_V":{"0":286.032, "1":286.207}}')

as.data.frame(fromJSON(json))

Can it be that you have a duplicate key?

I also tried the following (this should be equivalent to the correct answer).

library(jsonlite)

json <- as.character(
  '{"central_time":{"0":"2020-04-06 15:47:00","1":"2020-04-06 15:47:15"}, "Va_V":{"0":286.032, "1":286.207}}')

from.json <- fromJSON(json)
from.json <- t(from.json)
df <- do.call(cbind, from.json)

I know that you have already marked the correct answer, but can you please try the code nevertheless? I'm just curious what went wrong.

MacOS
  • 1,149
  • 1
  • 7
  • 14