HUGO

Converts a variable with markdown content in escaped html for JSON output

I have in pages, front matter :

{
"title": "Title",
"description" :  "# Heading 1 \n * List item \n * List item"
}

and I want if possible to output JSON format for categories pages

[
    {{ range $index, $e := .Pages }}
        {{ $title := .Title }}
        {{ $description := .Params.description }}
        {{ if $index }}, {{ end }}
        {
            "title": "{{ $title }}",
            "description" : "{{ $description }}"
        }
    {{ end }}
]

Unfortunately the final JSON comes with “Error: Parse error on line …” the reason is the $description.
How I can convert this value to be parsed to JSON correctly?

I ran throw your code, and it’s giving me the perfect output

[
  {
    "title": "Test Page",
    "description" : "this is meta description"
  }, 
  {
    "title": "Test Page 2",
    "description" : "this is meta description"
  }
]

maybe you should try this code and check what it returns

[
  {{ range $index, $e := .Pages }}
  {{ $title := .Title }}
  {{ $description := .Params.description }}
  {{ if $description }}
  {{ if $index }}, {{ end }}
  {
    "title": "{{ $title }}",
    "description" : "{{ $description }}"
  }
  {{ end }}
  {{ end }}
]

Try to use markdown in description please:

"description" :  "# Heading 1 \n * List item \n * List item"

Unable to test right now but I think you need to at least escape $description.

Are you looking to keep $description as markdown inside your JSON or convert to HTML?

I want to convert it to HTML

I try

{{ $description := markdownify .Params.description | htmlEscape }}

without result

I found the solution, I’ll let it here for others:
The problem was that in JSON template you need to let quotes (") out like here:

 "description" : {{ $description }},

not like here

 "description" : "{{ $description }}",

and prepare the value as below:

    {{- $description := jsonify ( markdownify .Params.description ) -}}
1 Like

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