skip to Main Content

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


  1. You want to convert the JavaScript object to the JSON string. You can do this using the JSON.stringify method.

    var f = JSON.stringify({street: street, location: location, number: number});
    

    Refer this:
    How to convert variables into json?

    Login or Signup to reply.
  2. You are using template strings so you need to add the variable using ${} AND quotes around string variables like this

    const userJSON = `{ "playerName": "${userName}" }`; 
    

    OR create the object and stringify it (makes more sense)

    const userOBJ = { "playerName": userName }; 
    const userJSON = JSON.stringify(userOBJ);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search