0

I'm using Sinatrarb to complete a task

I need to:

Parse the data of a JSON object from a url,

Single out one of attributes of the json data and store it as a variable

Run some arithmetic on the variable

Return the result as a new variable

then post this to a new url as a new json object.

I have seen bits and pieces of information all over including information on parsing JSON data in ruby and information on open-uri but I believe it would be very valuable having someone break this down step by step as most similar solutions given to this are either outdated or steeply complex.

Thanks in advance.

1 Answer 1

1

Here's a simple guide. I've done the same task recently.

Let's use this JSON (put it in a file called 'simple.json'):

{
    "name": "obscurite",
    "favorites": {
        "icecream": [
            "chocolate",
            "pistachio"
            ],
        "cars": [
            "ferrari",
            "porsche",
            "lamborghini"
        ]
    },
    "location": "NYC",
    "age": 100}

Parse the data of a JSON object from a url.

Step 1 is to add support for JSON parsing:

    require 'json'

Step 2 is to load in the JSON data from our new .json file:

    json_file = File.read('simple.json')
    json_data = JSON.parse(json_file)

Single out one of attributes of the json data and store it as a variable

Our data is in the form of a Hash on the outside (curly braces with key:values). Some of the values are also hashes ('favorites' and 'cars'). The values of those inner hashes are lists (Arrays in Ruby). So what we have is a hash of hashes, where some hashes are arrays.

Let's pull out my location:

    puts json_data['location'] # NYC

That was easy. It was just a top level key/value. Let's go deeper and pull out my favorite icecream(s):

    puts json_data['favorites']['icecream'] # chocolate pistachio

Now only my second favorite car:

    puts json_data['favorites']['cars'][1] # porsche

Run some arithmetic on the variable

Step 3. Let's get my age and cut it down by 50 years. Being 100 is tough!

    new_age = json_data['age'] / 2
    puts new_age

Return the result as a new variable

Step 4. Let's put the new age back into the json

    json_data['age'] = new_age
    puts json_data['age'] # 50

then post this to a new url as a new json object.

Step 5. Add the ability for your program to do an HTTP POST. Add this up at top:

    require 'net/http'

and then you can post anywhere you want. I found a fake web service you could use, if you just want to make sure the request got there.

# use this guy's fake web service page as a test. handy!
uri = URI.parse("http://jsonplaceholder.typicode.com/posts")
header = {'Content-Type'=> 'text/json'}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = json_data.to_json
response = http.request(request)

# Did we get something back?
puts response.body

On linux or mac you can open a localhost port and listen as a test:

    nc -4 -k -l -v localhost 1234

To POST to this port change the uri to:

    uri = URI.parse("http://localhost:1234")

Hope this helps. Let me know if you get stuck and I'll try to lend a hand. I'm not a ruby expert, but wanted to help a fellow explorer. Good luck.

Sign up to request clarification or add additional context in comments.

2 Comments

You're an everyday hero, my friend. Quick question though, I would need to source the initial json object from a website up online, as opposed to a file stored on my system- how would I go about this?
Glad I could help. The quick answer to your question is that you would look up the appropriate structure in the documentation for the API you are calling (that's why you're sending JSON in the first place, I assume). For example if a made up API required json like { "ID" : 123, "NAME" : "BOURNE" } then you would create a dictionary in python and then call the JSON serialization method (JSON.generate or json_data.to_json where json_data is your dict).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.