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

74 zobrazení
Přeskočit na první nepřečtenou zprávu

Nathan Waddell

nepřečteno,
2. 4. 2014 17:39:2702.04.14
komu: 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

nepřečteno,
3. 4. 2014 10:14:0503.04.14
komu: 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

nepřečteno,
3. 4. 2014 11:27:2503.04.14
komu: 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.

Odpovědět všem
Odpověď autorovi
Přeposlat
0 nových zpráv