A JSON string formatter. To define the callables that compute the JSONable representation of your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this. The return value of this format
| 806 | |
| 807 | |
| 808 | class JSONFormatter(BaseFormatter): |
| 809 | """A JSON string formatter. |
| 810 | |
| 811 | To define the callables that compute the JSONable representation of |
| 812 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
| 813 | or :meth:`for_type_by_name` methods to register functions that handle |
| 814 | this. |
| 815 | |
| 816 | The return value of this formatter should be a JSONable list or dict. |
| 817 | JSON scalars (None, number, string) are not allowed, only dict or list containers. |
| 818 | """ |
| 819 | format_type = Unicode('application/json') |
| 820 | _return_type = (list, dict) |
| 821 | |
| 822 | print_method = ObjectName('_repr_json_') |
| 823 | |
| 824 | def _check_return(self, r, obj): |
| 825 | """Check that a return value is appropriate |
| 826 | |
| 827 | Return the value if so, None otherwise, warning if invalid. |
| 828 | """ |
| 829 | if r is None: |
| 830 | return |
| 831 | md = None |
| 832 | if isinstance(r, tuple): |
| 833 | # unpack data, metadata tuple for type checking on first element |
| 834 | r, md = r |
| 835 | |
| 836 | # handle deprecated JSON-as-string form from IPython < 3 |
| 837 | if isinstance(r, str): |
| 838 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", |
| 839 | FormatterWarning) |
| 840 | r = json.loads(r) |
| 841 | |
| 842 | if md is not None: |
| 843 | # put the tuple back together |
| 844 | r = (r, md) |
| 845 | return super(JSONFormatter, self)._check_return(r, obj) |
| 846 | |
| 847 | |
| 848 | class JavascriptFormatter(BaseFormatter): |
no outgoing calls