How can I read the value of a JSON item?

I think this html is right.

<span id="tag_8" data-translations="{&quot;en&quot;:&quot;cat&quot;}" class="myTag selected">chat</span>at

# generated with : 
#  %span.myTag{:id => "tag_" + tag_id.to_s, :'data-translations' => translations(tag_id).to_json}= tag

      

I'm trying to read the translation from a jquery script, but it doesn't work:

selectedTag = $('#tag-list li span.myTag.selected:first')
console.log 'translations: ' + selectedTag.data("translations", "en")
 =>   translations: [object Object]

#however
 console.log 'translations: ' + selectedTag.data("translations")
 =>  translations: {"en"=>"cat"}

      

+3


source to share


1 answer


if you want to return cat you can do it like this

$ ('# TAG_8'). Data ('translations'). Gp



else if you want to return an object and store it in a variable you can do it like this var obj = $('#tag_8').data('translations')

and use it likeobj.en

$('#tag_8').data('translations')

returns

Object {en: "cat"}

/////////////////

$('#tag_8').data('translations').en

returns "cat"

      

+1


source







All Articles