Script Bytes

Tutorials and Tips for Angular, .Net, and More

Multi-line JSON Strings in Typescript

Jeff F
Jeff F
Cover Image for Multi-line JSON Strings in Typescript

I recently ran into an issue where I had a long string in one of our angular components typescript file that was getting parsed into JSON. The string was too long and TS Lint wasn't happy about it being so long because I use the max-line-length rule, and it's set to 140 characters. The string was also a description used on our front end so it had to be rendered as a single line with no breaks in it. After trying a few things I discovered how to do multi-line JSON strings in typescript.

I had the whole json string inside back ticks (called template literals, on my opinion one of the coolest things of javascript/typescript):

Extra long string in JSON

To make TS Lint happy I just added line breaks with the enter key to make it multi-line. The trouble with this is the parsing fails because it's no longer valid JSON, and you get the error: "Unexpected token in JSON at position xx".

Solutions

There are a few things you can do to fix this issue. The solution I used was to escape the new lines with a backslash .

Long JSON string escaped with backslashes

With this TS Lint does not throw any errors, and it still renders as a single unbroken line in the html:

Multi-line JSON sentence still rendered as one, unbroken line Long sentence still rendered as one, unbroken line.

Another solution is to not use string literals and have each line be it's own string and append them line-by-line:

Long string broken manually as individual strings

A 3rd solution is to not modify the long string and just tell TS Lint to ignore it. You can tell the linter to ignore an individual line by adding this line before it // tslint:disable-next-line:max-line-length


Do you have any other methods for handling issues like this? Comment below or send me a tweet!