Hi i am using R with opencpu.right now i used jsonlite library to get my results in json format but unforutnately it fails. I got the output like this.
["A101 Prateek Wisteria Sector 77 Noida New Delhi","7780274.18056666","1"]
i want the output the output like this
{ "flag": "0", "property_details", "<<address>>", "estimate", "<<estimated value from R>>" }
here is my program
library(jsonlite)
delhi <- read.delim("delhi.tsv", na.strings = "")
delhi$lnprice <- log(delhi$price)
if(address1 %in% delhi$property_address_1)
{
data <- read.delim("UItest.txt", na.strings = "")
heddel <- lm(lnprice ~ bedrooms+ area+ bathrooms, data = delhi)
result <- predict(heddel,data)
final_prediction = exp(result)
property_details = address1
property_details
flag=1
estimated_value <- final_prediction
result <- c(property_details,estimated_value,flag)
col_headings <- c('property_details','estimated_value','flag')
names(result) <- col_headings
toJSON(result,Pretty=TRUE)
}
any help will be appreciated.
To get output resembling your desired result try defining your results
variable as a data.frame
rather than a named vector
.
Using some fictitious data on the key lines from your code:
> library(jsonlite)
> result <- c("xyz",123.45,1)
> col_headings <- c('property_details','estimated_value','flag')
> names(result) <- col_headings
> toJSON(result, pretty=TRUE)
["xyz", "123.45", "1"]
Now refactoring this code a little bit to use a data.frame
instead of a named vector
:
> result <- data.frame('property_details'="xyz",'estimated_value'=123.45,'flag'=1)
> toJSON(result,pretty=TRUE)
[
{
"property_details": "xyz",
"estimated_value": 123.45,
"flag": 1
}
]
This also has the side effect of not coercing integer
and numeric
values into character
strings.
You need to "transpose" the results. Consider:
library(jsonlite)
col_headings <- c('property_details','estimated_value','flag')
result <- c("PropDetails", 1.1, TRUE)
results=data.frame(t(result))
names(results)=col_headings
Then:
toJSON(results)
produces:
[{"property_details":"PropDetails","estimated_value":"1.1","flag":"TRUE"}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.