Not able to parse JSON in ruby on rails using function JSON.parse -
i have following function in controller file have string , trying parse using json.parse. problem facing not able print value of message present in hash being returned.
def index ......... r = '{"response":"{\"message\":\"the following page created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}"}' @hash = json.parse(r) respond_to |format| format.html end end in view file using following code
<%= @hash['response']['message'] %> the output getting message instead of getting the following page created 3035
i have 'require json' on controller file.
if
<%= @hash['response'] %> then whole hash.please
the json string looks off. contains single key/value pair, key being response , rest being string containing looks escaped json:
"{\"message\":\"the following page created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}" in other words, behavior you're seeing expected given input you're giving.
if change json input (ie making sure value in response isn't given json-encoded string):
r = '{"response":{"message":"the following page created 3035","success":"0","page_id":"3035"}}' i imagine it'll work expect.
the reason @hash['response']['message'] returning "message" because @hash['response'] string. sending [] string string parameter results in parameter string being returned if occurs in recipient string:
"foobar"["bar"] #=> "bar" "foobar"["baz"] #=> nil see string#[] details.
Comments
Post a Comment