2

我的数据框包含如下数据:

Tester   W1  W2  W3   A   P  WD(%)   TS(Hrs.)   AT(Hrs.)    SU(%) 
a        60  40  102 202 150  100     120         120       100
b        30  38   46 114 150  76      135         120       100
c        25  30   52 107 150  71      120         120       100

通过使用jsonlite我已转换为 json 格式的包:

{
 "Tester": [ "a", "b", "c" ],
 "W1": [ 60, 30, 25],
 "W2": [ 40, 38, 30 ],
 "W3": [ 102, 46, 52 ],
 "A": [ 202, 114, 107 ],
 "P": [ 150, 150, 150 ],
 "WD...": [ 100, 76, 71 ],
 "TS.Hrs..": [ 120, 135, 120 ],
 "AT.Hrs..": [ 120, 120, 120 ],
 "SU...": [ 100, 100, 100 ] 
}

但我的要求是获得 JSON 格式,如:

[ {
    "Tester":"a"
    "W1": 60,
    "w2": 40
    "w3": 102,
    "A": 202
    "P": 150,
    "WD(%)":100,
    "TS (Hrs.) ": 120,
    "AT (Hrs.)": 120,
    "SU(%)": 100
}]

有人可以帮帮我吗?

4

1 回答 1

6

jsonlite当数据集是列表时,您看到的输出是由 产生的:

library(jsonlite)
toJSON(as.list(head(iris)))

{"Sepal.Length":[5.1,4.9,4.7,4.6,5,5.4],"Sepal.Width":[3.5,3,3.2,3.1,3.6,3.9],"Petal.Length":[1.4,1.4,1.3,1.5,1.4,1.7],"Petal.Width":[0.2,0.2,0.2,0.2,0.2,0.4],"Species":["setosa","setosa","setosa","setosa","setosa","setosa"]} 

确保您的数据集确实是一个数据框,并且您将看到预期的输出:

library(jsonlite)
toJSON(head(iris), pretty = TRUE)

[
    {
        "Sepal.Length": 5.1,
        "Sepal.Width": 3.5,
        "Petal.Length": 1.4,
        "Petal.Width": 0.2,
        "Species": "setosa"
    },
    {
        "Sepal.Length": 4.9,
        "Sepal.Width": 3,
        "Petal.Length": 1.4,
        "Petal.Width": 0.2,
        "Species": "setosa"
    },
    {
        "Sepal.Length": 4.7,
        "Sepal.Width": 3.2,
        "Petal.Length": 1.3,
        "Petal.Width": 0.2,
        "Species": "setosa"
    },
    {
        "Sepal.Length": 4.6,
        "Sepal.Width": 3.1,
        "Petal.Length": 1.5,
        "Petal.Width": 0.2,
        "Species": "setosa"
    },
    {
        "Sepal.Length": 5,
        "Sepal.Width": 3.6,
        "Petal.Length": 1.4,
        "Petal.Width": 0.2,
        "Species": "setosa"
    },
    {
        "Sepal.Length": 5.4,
        "Sepal.Width": 3.9,
        "Petal.Length": 1.7,
        "Petal.Width": 0.4,
        "Species": "setosa"
    }
]
于 2015-04-13T08:54:26.417 回答