json_editor_documentation.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo(ui.json_editor)
  4. def main_demo() -> None:
  5. json = {
  6. 'array': [1, 2, 3],
  7. 'boolean': True,
  8. 'color': '#82b92c',
  9. None: None,
  10. 'number': 123,
  11. 'object': {
  12. 'a': 'b',
  13. 'c': 'd',
  14. },
  15. 'time': 1575599819000,
  16. 'string': 'Hello World',
  17. }
  18. ui.json_editor({'content': {'json': json}},
  19. on_select=lambda e: ui.notify(f'Select: {e}'),
  20. on_change=lambda e: ui.notify(f'Change: {e}'))
  21. @doc.demo('Validation', '''
  22. You can use the `schema` parameter to define a [JSON schema](https://json-schema.org/) for validating the data being edited.
  23. In this demo, the editor will warn if the data does not match the schema:
  24. - `id` must be an integer
  25. - `name` must be a string
  26. - `price` must be a number greater than 0
  27. *Added in version 2.8.0*
  28. ''')
  29. def schema_demo() -> None:
  30. schema = {
  31. 'type': 'object',
  32. 'properties': {
  33. 'id': {
  34. 'type': 'integer',
  35. },
  36. 'name': {
  37. 'type': 'string',
  38. },
  39. 'price': {
  40. 'type': 'number',
  41. 'exclusiveMinimum': 0,
  42. },
  43. },
  44. 'required': ['id', 'name', 'price'],
  45. }
  46. data = {
  47. 'id': 42,
  48. 'name': 'Banana',
  49. 'price': 15.0,
  50. }
  51. ui.json_editor({'content': {'json': data}}, schema=schema)
  52. @doc.demo('Run methods', '''
  53. You can run methods of the JSONEditor instance using the `run_editor_method` method.
  54. This demo shows how to expand and collapse all nodes and how to get the current data.
  55. The colon ":" in front of the method name "expand" indicates that the value "path => true" is a JavaScript expression
  56. that is evaluated on the client before it is passed to the method.
  57. Note that requesting data from the client is only supported for page functions, not for the shared auto-index page.
  58. ''')
  59. def methods_demo() -> None:
  60. # @ui.page('/')
  61. def page():
  62. json = {
  63. 'Name': 'Alice',
  64. 'Age': 42,
  65. 'Address': {
  66. 'Street': 'Main Street',
  67. 'City': 'Wonderland',
  68. },
  69. }
  70. editor = ui.json_editor({'content': {'json': json}})
  71. ui.button('Expand', on_click=lambda: editor.run_editor_method(':expand', 'path => true'))
  72. ui.button('Collapse', on_click=lambda: editor.run_editor_method(':expand', 'path => false'))
  73. ui.button('Readonly', on_click=lambda: editor.run_editor_method('updateProps', {'readOnly': True}))
  74. async def get_data() -> None:
  75. data = await editor.run_editor_method('get')
  76. ui.notify(data)
  77. ui.button('Get Data', on_click=get_data)
  78. page() # HIDE
  79. doc.reference(ui.json_editor)