Python Array JSON (dumps) -
google app engine, python27
i trying encode python array of strings json string send client. created working solution, requires me manually create string version of array , call dumps on python, don't believe should necessary:
def get_json(cls): name_query = cls.query() array_string = "[" index = 1 name in name_query: array_string += '"' + name.key.id() + '"' if index < name_query.count(): array_string += ", " index += 1 array_string += "]" return json.dumps(array_string) >> "[\"billy\", \"bob\"]" for second attempt, tried calling "dumps" on python array, believe should working solution; instead, have call dumps twice:
# (bad output) def get_json(cls): name_query = cls.query() name_array = [] name in name_query: name_array.append(name.key.id()) return json.dumps(name_array) >> ["billy", "bob"] # (working output) def get_json(cls): name_query = cls.query() name_array = [] name in name_query: name_array.append(name.key.id()) return json.dumps(json.dumps(name_array))) >> "[\"billy\", \"bob\"]" even though have working solution, there better way , why calling dumps on python array not give correct output?
the first function working fine; it's outputting valid json string. think confusion it's not surrounded in double-quotes, that's because you're printing output of function.
it's returning string containing json list, not python list object:
>>> def get_json(): ... x = ["billy", "bob"] ... return json.dumps(x) ... >>> print get_json() ["billy", "bob"] >>> print repr(get_json()) '["billy", "bob"]' # it's string, not list >>> type(get_json()) <type 'str'> # see? type str when call json.dumps twice, you're wrapping python string returned first json.dumps call in double-quotes, , double-quotes inside array escaped, because they're embedded in 1 big json string now, instead of being used quotes around json strings inside json array.
>>> print repr(json.dumps(get_json())) '"[\\"billy\\", \\"bob\\"]"'
Comments
Post a Comment