Chapter 14.3.6. JSON Serialization

The JavaScript Object Notation (JSON) format was discussed earlier in Chapter 9, “Ajax and WhatWhat Status Projects.” TurboGears includes simplejson in Python to do conversions to and from JSON on the server. MochiKit enables you to do similar conversions on the browser side.

Converting from JSON to JavaScript is easy because JSON is, by definition, valid JavaScript. MochiKit includes an evalJSON function that simply wraps the JSON in parenthesis and runs eval on it.

MochiKit also includes a companion serializeJSON function to take JavaScript values and turn them into valid JSON. Many values work just as you’d expect:

 >>> serializeJSON(1) "1" >>> serializeJSON("Hello") "\"Hello\"" >>> serializeJSON([1,2,3]) ...

Get Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.