Using Ruby, grab value from HTML string inside a JSON response

Viewed 513

I have searched what I can and I don't seem to be finding the answer I need. Granted I may not be wording it properly. I have tried using .find or even .rindex to count backwards, but no such luck. The value I receive from the JSON looks something like this:

"AdditionalData":"<Data><Entry Key=\"utm_campaign\" Value=\"j2c\" /> 
<Entry Key=\"utm_medium\" Value=\"cpc\" /><Entry Key=\"utm_source\" 
Value=\"j2c\" /><Entry Key=\"job_id\" Value=\"300_xxxx_10703\" /></Data>"

I need to be able to grab the value for the key "job_id", so the "300_xxxx_11233". This value will change per object returned by the JSON response. Any help would be appreciated, and please let me know if this is already out there and I just missed it.

1 Answers

If the response format remains the same with every request, you could use a plain regexp expression to fetch your data, even without parsing JSON. Example:

response = "<Data><Entry Key=\"utm_campaign\" Value=\"j2c\" /><Entry Key=\"utm_medium\" Value=\"cpc\" /><Entry Key=\"utm_source\" Value=\"j2c\" /><Entry Key=\"job_id\" Value=\"300_xxxx_10703\" /></Data>"
match = response.match(%r{job_id\\?"\s+Value=\\?"(.+)\\?"}i)
match[1] if match # => "300_xxxx_10703"

If the response format can change (for example, if the order of the attributes of Entry element can change), then you need to parse JSON and use some HTML parser, such as Nokigiri, to fetch required attrbute. Code example:

parsed_response = JSON.parse(response)
doc = Nokogiri::HTML(parsed_response['AdditionalData'])

job_id = nil
doc.css('Entry').each do |el|
  if el['Key'] == 'job_id'
    job_id = el['Value']
    break
  end
end
Related