Mojo::JSON and Mojolicious::Controller::render confusion

瀏覽次數:74 次
跳到第一則未讀訊息

Nathan Waddell

未讀,
2014年4月2日 下午5:39:272014/4/2
收件者:mojol...@googlegroups.com
I'm working on a suite of HTTP/REST JSON web services, but running into a little strangeness. I figured I'm probably just not doing this right, so I'm posting here for clarification.

I am encoding LDAP attribute:value pairs to a hash, then encoding the hash to JSON. However, when I pass this encoded JSON to the render method of M::Controller, I get some strange escaping unless I specify it as 'data'.

Encoding data pulled from the Net::LDAP::Entry object:
@attrs = $entry->attributes;
foreach my $attr(@attrs) { $value = $entry->get_value($attr); $output{$attr} = $value;}
$json_output = $json->encode(\%output);

When I print out $json_output, everything is nicely encoded as I expect. It is when I try to render the response that I run into trouble unless I specify the 'data' directive.

So the following snippet:
return $c->render( data => $json_output, status => 200)  gives me {"someattribute":"somevalue"} as expected.

but:
return $c->render( json => $json_output, status => 200) gives me "{\"someattribute\":\"somevalue\"}" which I didn't expect.

I would love to be able to pass an unencoded hash into the 'json' method like so:

return $c->render( json => %output, status => 200)

or pass by reference:
return $c->render( json => \%output, status => 200)

but these exhibit the same behavior.

1.) What is causing this escaping behavior? I suspect it's something like I'm completely misunderstanding the 'json' directive to the render method.

2.) Is there a better way to pass a hash so that it is automatically encoded?

Any finger pointing in the appropriate direction is greatly appreciated.

sri

未讀,
2014年4月3日 上午10:14:052014/4/3
收件者:mojol...@googlegroups.com
1.) What is causing this escaping behavior? I suspect it's something like I'm completely misunderstanding the 'json' directive to the render method.

It's simply what's supposed to happen when you JSON encode a string.


--
sebastian

Nathan Waddell

未讀,
2014年4月3日 上午11:27:252014/4/3
收件者:mojol...@googlegroups.com
Ok. I see where I'm going wrong. Thanks!


--
You received this message because you are subscribed to a topic in the Google Groups "Mojolicious" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mojolicious/_oLqfHITukw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mojolicious...@googlegroups.com.
To post to this group, send email to mojol...@googlegroups.com.
Visit this group at http://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.

回覆所有人
回覆作者
轉寄
0 則新訊息