I am very new to JSON. I am writing a program in JavaScript and have tried looking for a simple answer. I guess I don’t know how to ask it right.
I want the user to input their information and it will be added into a JSON object. But I cannot get JSON to accept the value.
Let’s assume that userName="Bob"
.
const userJSON=`{
"playerName": userName
}`;
I want userJSON
to be "playerName": "Bob"
It keeps giving me an error saying that userName
is not valid JSON.
Is there a simple way to do this?
I can get it to parse out information if it is "playerName":"Bob"
but this is part of a game that people need to be able to add their own usernames.
2
Answers
You want to convert the JavaScript object to the JSON string. You can do this using the
JSON.stringify
method.Refer this:
How to convert variables into json?
You are using template strings so you need to add the variable using
${}
AND quotes around string variables like thisOR create the object and stringify it (makes more sense)