Json linebreaks in .Content

I suspect a bug: the Json output generates a linebreak for .Content

my item.json.json looks like this:
{
“title”: “{{ .Title }}”,
“date”: “{{ .Date }}”,
“type”: “{{ .Type }}”,
“content”: “{{ .Content | plainify }}”,
“permalink”: “{{ .RelPermalink }}”,
}

and all items for .Content end with the closing apostrophe along with the comma on a new line. This causes my javascript JSON.parse to complain.

A similar issue was raised here

but he somehow managed to fix his data. I tried using trim on .Content but that did not prevent this.

Hugo 0.75.1
git@github.com:ourmaninindia/odyssey-tours.git

The last comma is not valid JSON. Post what exactly JSON.parse complains about and it will probably be that.

By the way: try jsonify:

{{ .Content | jsonify | safeJS }}

This might help with encoding special characters (like linebreaks).

1 Like

Ah sorry that comma I fixed. I was trying to see whether the position of the .Content line had some effect but it did not. JSON.parse complaint message is this:

Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 12 column 336 of the JSON data

where the literal is indeed a line break. If I add jsonify then it generates extra commas:
“content”: ““Agra is home …centuries.\n””

The standard data is output like this (i.e. a line break):
"Agra is home … centuries.
",

I also tried {{ substr .Content 0 -2 | plainify }} to get rid of the line break but that was not allowed:
error calling substr: calculated start position greater than end position: 0 > -2

Odd as the latter comes straight from the docs and I am pretty sure it works in a regular template layout

I solved my problem a different way: I replaced the line break using javascript just before json.parse

xhr.responseText.replace(/(\n)/gm,"");

That takes the pressure off though of course the issue is still there.

I thought we were talking about a linebreak inside of text. if it’s at the end, there is trim for it:

yes! This solved the issue:

{{ trim (.Content | plainify ) “\n” }}

It appeared that the plainify was actually the culprit.
Thanks a ton :slight_smile:

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