Skip to content
Advertisement

How to format a string of html in json

I am working on a tool for generating html files. The code is fairly simple. A user clicks a post button and the content from a textarea is sent to an endpoint. I have tried posting the html as a json string.

Expected The saveContent method is called. The value from the textarea element is concatenated into a string. This string is the json that is sent to the server. Once the request is completed a 201 response should come back.

Actual The saveContent method is called. The value from the textarea element is concatenated into a string. This string is the json that is sent to the server. A 400 response comes back.

Here is an example of the string

JavaScript

This is the saveContent method

JavaScript

Advertisement

Answer

Don’t create JSON by concatenating strings. You’re not properly escaping all the nested quotes, converting newlines to n, etc.

Use JSON.stringify() on a JavaScript object:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement