This question already has an answer here:
- Parsing a JSON string in Ruby 7 answers
I'm looking for a simple way to parse JSON, extract a value and write it into a database in Rails.
Specifically what I'm looking for, is a way to extract shortUrl
from the JSON returned from the bit.ly API:
{
"errorCode": 0,
"errorMessage": "",
"results":
{
"http://www.foo.com":
{
"hash": "e5TEd",
"shortKeywordUrl": "",
"shortUrl": "http://bit.ly/1a0p8G",
"userHash": "1a0p8G"
}
},
"statusCode": "OK"
}
And then take that shortUrl and write it into an ActiveRecord object associated with the long URL.
This is one of those things that I can think through entirely in concept and when I sit down to execute I realize I've got a lot to learn.
Here's what I would do:
If you know the source url then you can use:
If you don't know the key for the source url you can do the following:
If you're not wanting to lookup keys using symbols, you can convert the keys in the hash to strings:
If you're concerned the JSON structure might change you could build a simple JSON Schema and validate the JSON before attempting to access keys. This would provide a guard.
NOTE: Had to mangle the bit.ly url because of posting rules.
These answers are a bit dated. Therefore I give you:
Rails should automagically load the
json
module for you, so you don't need to addrequire 'json'
.Parsing JSON in Rails is quite straightforward:
Let's suppose, the object you want to associate the shortUrl with is a Site object, which has two attributes - short_url and long_url. Than, to get the shortUrl and associate it with the appropriate Site object, you can do something like:
work with the hash and do what you want to do.
RUBY is case sensitive.
for example
Ruby has a JSON parser: