Search code examples
javascriptjsonstringifyjsonparser

How to pass variable to JSON without printing it as String


How to pass variable to JSON object and print it like JSON object?

I simply want to pass variable value in JSON and print it like JSON which can also be used in console.table(obj)

With Stringify:

var name = "someName";
const json = JSON.stringify('{"result":'+name+', "count":42}');
const obj = JSON.parse(json);
console.log(obj);

Without stringify

var name = "someName";
const json = '{"result":'+name+', "count":42}';
const obj = JSON.parse(json);
console.log(obj);

Using \"variableName\" it gets value in \"...\" and not the variable value

var name = "someName";
const json = '{"result":\"name\", "count":42}';
const obj = JSON.parse(json);
console.log(obj);


Solution:

var debugJSON = [];
var section_number = 1;
var i = 25;
var x = section_number-i;
tempJSON = {
        "section" : section_number, 
        "index" : i, 
        "fieldname" : x,
        "isValid" : "not required"
};              
    
debugJSON.push(tempJSON);

console.log(debugJSON);     
//console.table(debugJSON); //Problematic on Chrome Browser and Stack Overflow


Solution

  • A JSON is quite literally a JavaScript object, so you don't treat it as a string, you work with objects, which you can later stringify if need be.

    In your case, you don't want to pass a variable in a string, you should pass it in an object like so:

    // Declaration of name
    let name = 'someName';
    
    // Create object and store name
    const json = {
      result: name,
      count: 42
    };
    
    // Log object as JSON and as string
    console.log(json);
    console.log(JSON.stringify(json));

    The first log returns your object as exactly that, an object, the second log, converts it into a string to do so as you please with it!