Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More accurately parse json values for params #1661

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions spec/lucky/params_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,16 @@ describe Lucky::Params do
params.nested?(:user).should eq({"name" => "Bunyan", "age" => "102", "active" => "true"})
end

it "gets nested JSON containing nested JSON" do
request = build_request body: {user: {name: "Paul", address: {home: "1600 Pennsylvania Ave"}}}.to_json,
content_type: "application/json"
request.query = "from=query"

params = Lucky::Params.new(request)

params.nested?(:user).should eq({"name" => "Paul", "address" => "{\"home\":\"1600 Pennsylvania Ave\"}"})
end

it "gets nested multipart params" do
request = build_multipart_request form_parts: {
"user" => {
Expand Down
12 changes: 8 additions & 4 deletions src/lucky/params.cr
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ class Lucky::Params
nested_key_json = parsed_json[nested_key]? || JSON::Any.new({} of String => JSON::Any)

nested_key_json.as_h.each do |key, value|
nested_params[key.to_s] = value.to_s
nested_params[key.to_s] = stringify_json_value(value)
end

nested_params
Expand All @@ -423,7 +423,7 @@ class Lucky::Params

nested_key_json.as_h.each do |key, value|
if array_value = value.as_a?
nested_params[key.to_s] = array_value.map(&.to_s)
nested_params[key.to_s] = array_value.map { |array_val| stringify_json_value(array_val) }
end
end

Expand Down Expand Up @@ -535,7 +535,7 @@ class Lucky::Params
nested_key_json.as_a.each do |nested_values|
nested_params = {} of String => String
nested_values.as_h.each do |key, value|
nested_params[key.to_s] = value.to_s
nested_params[key.to_s] = stringify_json_value(value)
end

many_nested_params << nested_params
Expand Down Expand Up @@ -573,7 +573,7 @@ class Lucky::Params

private def body_param(key : String)
if json?
parsed_json[key]?.try(&.to_s)
parsed_json[key]?.try { |value| stringify_json_value(value) }
elsif multipart?
multipart_params[key]?
else
Expand Down Expand Up @@ -654,4 +654,8 @@ class Lucky::Params
nil
end
end

private def stringify_json_value(value : JSON::Any) : String
value.as_s? || value.to_json
end
end