Thursday 15 March 2012

Ruby and JSON: Making accessing objects more tolerant -


I'm working with some JSON which is "flexible", there will be an object array in some cases Sometimes it can be a string, and sometimes it can not be present at all, it is also a very deep nest. For example, API calls a list of results, and each result can have zero, one or several thumbnails. I want to return the thumbnails if there is only one, if there are many earlier, or zero if none is there.

Is there an easy way to do this Ruby's JSON library?

At the moment, I am doing something like:

  def get_thumbnail if @ Jason [ "Results"] Result = @ Jason [ "Results"]. First thumbnail = result ['thumbnail'] if thumbnail thumbnail.class == string thumbnail elsim thumbnail.class == array thumbnail.First second zero end and zero end end   

< P> Thanks in advance. In addition to checking the presence and type of each 'level', is there a more tolerant way to access JSON?

If you want to work on the way, can it force you. In this way, you can avoid checking the presence of things continuously and only what is there or work with proper defaults.

  def thumbnail (json) thumbnail_record (json). First end def thumbnail_record jsn) Array (first_record (jsn) ['thumbnail']) End DEF first_record (jsn) result (jsn) results: fast || {} Def end result (Jesan) Arre (Jesn [ "Results"]) end    

No comments:

Post a Comment