在“中解析JSON”;R";

在“中解析JSON”;R";,r,json,parsing,R,Json,Parsing,我正在学习“R”,所以这个问题对你们大多数人来说可能微不足道 我想从中创建数据帧 JSON如下所示: { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "MSFT", "3. Last Refreshed": "2019-05-17 10:01:49", "4. Output Size": "Compact",

我正在学习“R”,所以这个问题对你们大多数人来说可能微不足道

我想从中创建数据帧

JSON如下所示:

{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2019-05-17 10:01:49",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2019-05-17": {
        "1. open": "128.3050",
        "2. high": "129.0600",
        "3. low": "128.2700",
        "4. close": "128.8200",
        "5. volume": "3817460"
    },
    "2019-05-16": {
        "1. open": "126.7500",
        "2. high": "129.3800",
        "3. low": "126.4600",
        "4. close": "128.9300",
        "5. volume": "29676333"
    },
 ...
 }
}
我想将其解析为一个表,其中包含列
day | open | high | low | close | volume


我可以不用for循环吗?

为了解析JSON文件,最好使用
jsonlite
库。它可以完美地处理“简单”的JSON文件,这些文件可以直接解析为数据帧。然而,您的输入文件并不是那么容易,所以您需要将读取文件分解为几个步骤,以获得格式良好的数据帧

library(jsonlite)
library(dplyr)
library(tibble)
library(stringi)
df <- data.frame(do.call(rbind, fromJSON("./example.json")[[2]]))
dates <- as.Date(rownames(df), format="%Y-%m-%d")
df <- df %>% mutate_all(as.numeric) %>% add_column(dates, .before=1)
colnames(df) <- stri_trans_totitle(stri_replace_all_regex(colnames(df), "X\\d\\.\\.", ""))
library(jsonlite)
图书馆(dplyr)
图书馆(tibble)
图书馆(stringi)

df使用
fromJSON()
jsonlite
包读取数据集:

x=fromJSON('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo')
x2 = spread(plyr::ldply(x$`Time Series (Daily)`, stack), key = ind, value = 'values')
使用
plyr:ldply
取消堆叠时间序列子列表的结果,然后使用
spread()
tidyr
包将数据从长到宽进行转换:

x=fromJSON('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo')
x2 = spread(plyr::ldply(x$`Time Series (Daily)`, stack), key = ind, value = 'values')
根据需要重命名列:

colnames(x2) = c('day', 'open', 'high', 'low', 'close', 'volume')

您可以使用Alphavantage服务的现有访问器,请参阅@DirkEddelbuettel谢谢,我不知道,我会调查的。太棒了!谢谢你的回答。