to XML() or to JSON.parse() ?

112 views
Skip to first unread message

Pierre

unread,
Jul 28, 2017, 11:21:22 AM7/28/17
to web2py-users

Hi everyone,

I'd prefer JSON.parse() but in most case i have to fall back on XML()

for example given a list


alist= ["it's ok","I'm late"]


If an AJAX function returns something of the form:


 return json.dumps(dict(alist=alist, astring='abcd'))


then JSON.parse() can cope with it


howewer if it returns a 'hybrid' type like:


return dict(astring='abcd', ajson=json.dumps(alist))

then the json part can only be decoded by XML()


Is this what's expected ? Or do i miss something ?





third option would be 'very deep snorkeling'

Anthony

unread,
Jul 28, 2017, 12:11:32 PM7/28/17
to web2py-users
Whenever an action returns a dictionary, web2py looks for and executes an associated view (and if a view is not found, it uses a generic view if the generic view has been enabled). Are you returning a dictionary because you want to execute a view, or do you simply want to return the entire dictionary converted to JSON? If the latter, wrap the entire dictionary in json.dumps(). If the former, what does the view look like?

Anthony

Pierre

unread,
Jul 28, 2017, 3:56:45 PM7/28/17
to web2py-users
Yes I want to execute a view here is the example code:

Controller:

from json import dumps as jdumps

def abtest():
    alist
= ["it's ok","I'm late"]
   
return dict(stra='abcd', obj=jdumps(alist))

View:

{{extend 'layout.html'}}
<h1>Ceci est le modèle test/abtest.html </h1>
<h1 id='result'>
    RESULT
</
h1>
<script>
var o= "{{=obj}}";
var po = JSON.parse(o);
console
.log(po);
jQuery
("#result").html(po);
</script>


JSON decode error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Anthony

unread,
Jul 28, 2017, 4:46:30 PM7/28/17
to web2py-users
Yes, as usual, if you want to prevent escaping in the view, you must wrap with XML(). Another options is:

Controller:

    return dict(stra='abcd', obj=alist) # No JSON conversion needed here.

View:

<script>
{{=ASSIGNJS(o=obj)}}
...

The ASSIGNJS helper will handle everything.

Anthony

Pierre

unread,
Jul 31, 2017, 10:54:10 AM7/31/17
to web2py-users
thanks Anthony

I'll use ASSIGNJS. I'd never heard of this helper.....too bad it's unpublished in the book....

lyn2py

unread,
Jul 31, 2017, 10:45:57 PM7/31/17
to web2py-users
new helper?

Massimo Di Pierro

unread,
Aug 4, 2017, 10:48:36 AM8/4/17
to web2py-users
It has been around for more than one year. It is an oversight that it is not in the book.

Dave S

unread,
Aug 4, 2017, 4:56:41 PM8/4/17
to web2py-users


On Friday, August 4, 2017 at 7:48:36 AM UTC-7, Massimo Di Pierro wrote:
It has been around for more than one year. It is an oversight that it is not in the book.


I noticed that when I was looking up the posts.  Nov '14.

/dps


 
Reply all
Reply to author
Forward
0 new messages