0

Still new to Ruby - I apologize in advance if this has been asked.

I am using HTTParty to get data from an API, and it is returning an array of JSON data that I can't quite figure out how to parse.

#<Net::HTTPOK:0x1017fb8c0>
{"ERRORARRAY":[],"DATA":[{"ALERT":1,"LABEL":"hello","WATCHDOG":1},{"LABEL":"goodbye","WATCHDOG":1}

I guess the first question is that I don't really know what I am looking at. When I do response.class I get HTTParty::Response. It appears to be a Hash inside an array? I am not sure. Anyway, I want a way to just grab the "LABEL" for every separate array, so the result would be "hello", "goodbye". How would I go about doing so?

3 Answers 3

1

you don't need to parse it per say. what you could do is replace ':' with '=>' and evaluate it.

example: say you have ["one":"a","two":"b"], you could set s to equal that string and do eval s.gsub(/^\[/, '{').gsub(/\]$/, '}').gsub('":', '"=>') will yield a ruby hash (with inspect showing {"one"=>"a", "two"=>"b"})

alternatively, you could do something like this

require 'json'

string_to_parse = "{\"one\":\"a\",\"two\":\"b\"}"

parsed_and_a_hash = JSON.parse(string_to_parse)

parsed_and_a_hash is a hash!

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

2 Comments

this is great, and i see where it is going. for some reason, i can't install the json gem (whole other issue). when i get a ruby hash with the regex, how do I access the elements in the hash? how would i list all of one key's value?
if you have a hash, say from my example, you would access the value corresponding to the key "one" with parsed_and_a_hash["one"]. to see all the keys, make a call the "keys" method like this: parsed_and_a_hash.keys
0

If that's JSON, then your best bet is to install a library that handles the JSON format. There's really no point in reinventing the wheel (although it is fun). Have a look at this article.

If you know that the JSON data will always, always be in exactly the same format, then you might manage something relatively simple without a JSON gem. But I'm not sure that it's worth the hassle.

Comments

0

If you're struggling with the json gem, consider using the Crack gem. It has the added benefit of also parsing xml.

require 'crack'
my_hash_array = Crack::JSON.parse(my_json_string)

my_hash_array = Crack::XML.parse(my_xml_string)

Comments

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.