Tuesday, 15 February 2011

python - json.dumps 'skip over' specific keys? -



python - json.dumps 'skip over' specific keys? -

is there way have python's json.dumps 'skip over' specific keys, values written straight tag?

for example

data = {'a_number': 42, 'a_string': 'foo'} data['a_json_encoded_object'] = '{"foo": "bar"}' #this string beingness read db dumped = json.dumps(data)

then in html file, using django

<script> var info = {{dumped}} </script>

this results in html of:

var info = {"a_json_encoded_object": "{\\"foo\\": \\"bar\\"}", "a_string": "foo", "a_number": 42}

but want is:

var info = {"a_json_encoded_object": {"foo": "bar"}, "a_string": "foo", "a_number": 42}

is there way that? i.e. tell json.dumps: key 'a_json_encoded_object', don't manipulate value @ all, , write json straight after "a_json_encoded_object":

if not, best practice getting json-encoded string db browser memory? reference, right i'm using json.parse, it's messy.

okay, you're trying accomplish effect of

data['a_json_encoded_object'] = {"foo": "bar"}

and have string

'{"foo": "bar"}'

from database.

simply utilize json.loads convert string python dictionary

>>> json.loads('{"foo": "bar"}') {u'foo': u'bar'}

so

data['a_json_encoded_object'] = json.loads('{"foo": "bar"}')

which same as

data['a_json_encoded_object'] = {"foo": "bar"}

in django template

<script> var info = {{ dumped|safe }} // mark safe quotations won't escaped </script>

which renders to

var info = {"a_json_encoded_object": {"foo": "bar"}, "a_string": "foo", "a_number": 42}

python json django-templates

No comments:

Post a Comment