{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# JSON 编辑器\n", "\n", "`JSONEditor` 是一个使用 [JSONEditor](https://github.com/josdejong/svelte-jsoneditor) 创建JSON编辑器的元素。通过更改`properties`属性,可以将更新推送到编辑器。数据发生变化后,调用`update`方法刷新编辑器。\n", "\n", "- `properties`: JSONEditor 属性的字典\n", "- `on_select`: 当某些内容被选中时调用的回调函数\n", "- `on_change`: 当内容发生变化时调用的回调函数" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "\n", "json = {\n", " 'array': [1, 2, 3],\n", " 'boolean': True,\n", " 'color': '#82b92c',\n", " None: None,\n", " 'number': 123,\n", " 'object': {\n", " 'a': 'b',\n", " 'c': 'd',\n", " },\n", " 'time': 1575599819000,\n", " 'string': 'Hello World',\n", "}\n", "ui.json_editor({'content': {'json': json}},\n", " on_select=lambda e: ui.notify(f'Select: {e}'),\n", " on_change=lambda e: ui.notify(f'Change: {e}'))\n", "\n", "# ui.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 运行方法\n", "\n", "你可以使用`run_editor_method`方法来运行JSONEditor实例的方法。这个示例展示了如何展开和折叠所有节点,以及如何获取当前数据。\n", "\n", "在方法名 `\"expand\"` 前面的冒号 `\":\"` 表示值 `\"path => true\"` 是一个JavaScript表达式,它在传递给方法之前会在客户端进行求值。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "\n", "json = {\n", " 'Name': 'Alice',\n", " 'Age': 42,\n", " 'Address': {\n", " 'Street': 'Main Street',\n", " 'City': 'Wonderland',\n", " },\n", "}\n", "editor = ui.json_editor({'content': {'json': json}})\n", "\n", "ui.button('Expand', on_click=lambda: editor.run_editor_method(':expand', 'path => true'))\n", "ui.button('Collapse', on_click=lambda: editor.run_editor_method(':expand', 'path => false'))\n", "ui.button('Readonly', on_click=lambda: editor.run_editor_method('updateProps', {'readOnly': True}))\n", "\n", "async def get_data() -> None:\n", " data = await editor.run_editor_method('get')\n", " ui.notify(data)\n", "ui.button('Get Data', on_click=get_data)\n", "\n", "# ui.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }