Home > Back-end >  What is the type of this string and how to convert it to hash?
What is the type of this string and how to convert it to hash?

Time:09-21

I passing ransack params from page to page. Initially params looks like hash

{"processed_at_gteq_datetime"=>"2021-08-01", "processed_at_lteq_datetime"=>"2021-09-14", "status_eq"=>"processed"}

But after sending this params to another page, it becomes a string and takes the following type:

"{\"processed_at_gteq_datetime\"=>\"2021-08-01\", \"processed_at_lteq_datetime\"=>\"2021-09-14\", \"status_eq\"=>\"processed\"}"

And in this form, I cannot use them for searching.

How i can convert this string:

"{\"processed_at_gteq_datetime\"=>\"2021-08-01\", \"processed_at_lteq_datetime\"=>\"2021-09-14\", \"status_eq\"=>\"processed\"}"

to hash?

I tried

JSON.parse my_params

But it doesn't work with this string

JSON::ParserError Exception: 767: unexpected token at '{"processed_at_gteq_datetime"=>"2021-08-01", "processed_at_lteq_datetime"=>"2021-09-14", "status_eq"=>"processed"}'

CodePudding user response:

I guess you are passing parameters from page to page using either a link or a redirect.

If you want to keep those params as such, you have to pass them to the path helper:

link_to other_page_path(ransack_hash)
# => /other_page?processed_at_gteq_datetime=2021-08-01&processed_at_lteq_datetime=2021-09-14&status_eq=processed

and similar constructs. This

link_to other_page_path(q: ransack_hash)
# => /other_page?q[processed_at_gteq_datetime]=2021-08-01&q[processed_at_lteq_datetime]=2021-09-14&q[status_eq]=processed

will nest the params so that you can then retrieve in the other controller with

ransack_params = params[:q]

CodePudding user response:

The reason this doesn't work:

JSON.parse("{\"foo\"=>\"bar\"}")

is because it's not valid Json. for valid JSON you need to replace the ruby => operator with the javascript : operator. You can do this with a ruby string manipulation.

string = "{\"foo\"=>\"bar\"}"
json = string.gsub(/=>/,':')
JSON.parse(json)
  • Related