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.
What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.
There are no security concerns possible. JSON isn't code, you can't inject harmful values into it. JSON. parse is safe.
These answers are a bit dated. Therefore I give you:
hash = JSON.parse string
Rails should automagically load the json
module for you, so you don't need to add require 'json'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With