toJSON()
Apart from converting JSON to R with fromJSON()
, you can also use toJSON()
to convert R data to a JSON format. In its most basic use, you simply pass this function an R object to convert to a JSON. The result is an R object of the class json
, which is basically a character string representing that JSON.
For this exercise, you will be working with a .csv
file containing information on the amount of desalinated water that is produced around the world. As you'll see, it contains a lot of missing values. This data can be found on the URL that is specified in the sample code.
This is a part of the course
“Intermediate Importing Data in R”
Exercise instructions
- Use a function of the
utils
package to import the.csv
file directly from the URL specified inurl_csv
. Save the resulting data frame aswater
. - Convert the data frame
water
to a JSON. Call the resulting objectwater_json
. - Print out
water_json
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# jsonlite is already loaded
# URL pointing to the .csv file
url_csv <- "https://assets.datacamp.com/production/course_1478/datasets/water.csv"
# Import the .csv file located at url_csv
# Convert the data file according to the requirements
# Print out water_json
This exercise is part of the course
Intermediate Importing Data in R
Parse data in any format. Whether it's flat files, statistical software, databases, or data right from the web.
Importing data from the web is one thing; actually being able to extract useful information is another. Learn more about the JSON format to get one step closer to web domination.
Exercise 1: APIs & JSONExercise 2: From JSON to RExercise 3: Import JSON data from APIExercise 4: OMDb APIExercise 5: JSON & jsonliteExercise 6: JSON practice (1)Exercise 7: JSON practice (2)Exercise 8: toJSON()Exercise 9: Minify and prettifyWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.