There is such a json

"threads": [{"posts": {"banned":0, "closed":0, "comment":}}] 

How to get data from comment from here?

I have this code

 require 'rubygems' require 'json' require 'httparty' file = File.read('test.json') data_hash = JSON.parse(file) posts_count = data_hash['posts_count'] posts = data_hash['posts'] threads = data_hash['threads'] length = threads.length p threads 

What to add to make it work? Because when I enter

 comment = data_hash['comment'] p comment 

he gives out nil

  • Add p data_hash at the end and attach the output to the question. - MAXOPKA
  • Is the structure exactly correct? If yes, then nothing should be displayed. At the root (read in data_hash) there is no comment field. - anoam
  • one
    You need a file structure and a description of what you need to get from it. - anoam

1 answer 1

The correct JSON code is:

 a='{"threads": [{"posts": {"banned":0, "closed":0, "comment":""}}]}' 
  1. There should not be an open dictionary ( Hash ) from the root of the tree, i.e. it must be enclosed in braces: {} .

  2. There should be no missing values, like the comment field, there should be either null or an empty string.

The above code is understood correctly:

 JSON.parse(a) # => {"threads"=>[{"posts"=>{"banned"=>0, "closed"=>0, "comment"=>""}}]}