# Using toJson in big search template

**URL:** <https://discuss.elastic.co/t/using-tojson-in-big-search-template/349951>\
**Category:** Elasticsearch\
**Created:** [December 26, 2023, 11:51am UTC](https://discuss.elastic.co/t/using-tojson-in-big-search-template/349951 "2023-12-26T11:51:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bertie](https://avatars.discourse-cdn.com/v4/letter/b/9de0a6/32.png) [@bertie](https://discuss.elastic.co/u/bertie)\
**Post date:** [December 26, 2023, 11:51am UTC](https://discuss.elastic.co/t/using-tojson-in-big-search-template/349951/1 "2023-12-26T11:51:18Z")

</div>

I cannot figure out how I should use the toJson when prototyping templates in the kibana dev console. If I simply use it like others mustache functions like the following example Kibana simply classifies it as a "bad string" and won't execute it (assuming the '{{#' syntax doesn't sit well with it):

```auto
POST _render/template
{
  "source": {
    "query": {
      "field": {{#toJson}}param{{/toJson}}
    }
  },
  "params": {
    "param": ["val1","val2"]
  }
}

```

If I wrap it in quotes (like the following example) elasticsearch returns a "json\_parse\_exception" with the reason being "Unclosed object or array found":

```auto
POST _render/template
{
  "source": {
    "query": {
      "field": "{{#toJson}}param{{/toJson}}"
    }
  },
  "params": {
    "param": ["val1","val2"]
  }
}

```

The documentation specifies that "To ensure the request body is valid JSON, the `source` is written in the string format" as in the following example (which works), but besides the fact that this is un-intuitive and seems like an unintended side-effect of something else, it also results in a block which Kibana won't syntax check (making it harder to prototype more complex templates):

```auto
POST _render/template
{
  "source": """{
    "query": {
      "field": {{#toJson}}param{{/toJson}}
    }
  }""",
  "params": {
    "param": ["val1","val2"]
  }
}

```

Is there's something that I'm missing? Is there a way to write large templates with toJson functionality and keep the kibana syntax highlighting and syntax check?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [January 23, 2024, 11:52am UTC](https://discuss.elastic.co/t/using-tojson-in-big-search-template/349951/2 "2024-01-23T11:52:08Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
