I am trying to parse the json data from an input field on my node.js server. If I simply have the value 16 as a value in the input field, I can simply read it out with request.body.id
(<input type="hidden" id="id" name="id" value="16"/>)
. But when I stringify a json as a value of the input field and parse the data of json, I always get an error SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)
. But I can see in the browser console my json data <input type="hidden" id="id" name="id" value="{" a":0.3,"b":0.5,"c":1.3}">
Why can't I read the value of the input field with request.body.id
?
CodePudding user response:
You need to send only the JSON data to the server while calling the respective endpoint in the front-end application. You should not send the html directly to the node js end-point
CodePudding user response:
The tag
<input type="hidden" id="id" name="id" value="{" a":0.3,"b":0.5,"c":1.3}">
contains the attributes
type="hidden"
id="id"
name="id"
value="{"
and some garbage
a":0.3,"b":0.5,"c":1.3}"
because the first quote in your JSON closes the attribute.
You have to masquerade the quotes
<input type="hidden" id="id" name="id" value="{" a":0.3,"b":0.5,"c":1.3}">
After clarification in the comments here is a working example:
const json = JSON.stringify({" a":0.3,"b":0.5,"c":1.3});
document.body.innerHTML = `<input value="${json.replaceAll('"', '"')}">`;
const input = document.querySelector('input');
console.log(JSON.parse(input.value));