From ef16a8ec54b1f7564deb3adc3d3c5abe68a80abc Mon Sep 17 00:00:00 2001 From: Toby Webb Date: Mon, 6 Dec 2021 23:31:17 +0100 Subject: [PATCH] vweb: add json_pretty method (#12745) --- vlib/vweb/vweb.v | 7 +++++++ vlib/vweb/vweb_app_test.v | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 88a43f275e..ce9b6affd7 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -244,6 +244,13 @@ pub fn (mut ctx Context) json(j T) Result { return Result{} } +// Response HTTP_OK with a pretty-printed JSON result +pub fn (mut ctx Context) json_pretty(j T) Result { + json_s := json.encode_pretty(j) + ctx.send_response_to_client('application/json', json_s) + return Result{} +} + // Response HTTP_OK with file as payload pub fn (mut ctx Context) file(f_path string) Result { ext := os.file_ext(f_path) diff --git a/vlib/vweb/vweb_app_test.v b/vlib/vweb/vweb_app_test.v index b2f9145bbe..70e24fa65e 100644 --- a/vlib/vweb/vweb_app_test.v +++ b/vlib/vweb/vweb_app_test.v @@ -64,3 +64,15 @@ pub fn (mut app App) new_article() vweb.Result { fn (mut app App) time() { app.text(time.now().format()) } + +fn (mut app App) time_json() { + app.json({ + 'time': time.now().format() + }) +} + +fn (mut app App) time_json_pretty() { + app.json_pretty({ + 'time': time.now().format() + }) +}