Serialize a Python object to a Flatted JSON string. This function converts `value`, a Python object (including those with circular references), into a JSON string that can be safely transmitted or stored. The resulting string can be reconstructed using Flatted's parse(). The `*
(value, *args, **kwargs)
| 190 | |
| 191 | |
| 192 | def stringify(value, *args, **kwargs): |
| 193 | """ |
| 194 | Serialize a Python object to a Flatted JSON string. |
| 195 | |
| 196 | This function converts `value`, a Python object (including those with |
| 197 | circular references), into a JSON string that can be safely transmitted |
| 198 | or stored. The resulting string can be reconstructed using Flatted's |
| 199 | parse(). The `*args` and `**kwargs` are passed to json.dumps() for |
| 200 | additional customization. |
| 201 | |
| 202 | ```python |
| 203 | from pyscript import flatted |
| 204 | |
| 205 | |
| 206 | # Create an object with a circular reference. |
| 207 | parent = {"name": "parent", "children": []} |
| 208 | child = {"name": "child", "parent": parent} |
| 209 | parent["children"].append(child) |
| 210 | |
| 211 | # Serialize it (standard json.dumps would fail here). |
| 212 | json_string = flatted.stringify(parent) |
| 213 | |
| 214 | # Can optionally pretty-print via JSON indentation etc. |
| 215 | pretty = flatted.stringify(parent, indent=2) |
| 216 | ``` |
| 217 | """ |
| 218 | known = _Known() |
| 219 | input = [] |
| 220 | output = [] |
| 221 | i = int(_index(known, input, value)) |
| 222 | while i < len(input): |
| 223 | output.append(_transform(known, input, input[i])) |
| 224 | i += 1 |
| 225 | return _json.dumps(output, *args, **kwargs) |
no test coverage detected