Home > Blockchain >  How to pass variable to JSON without printing it as String
How to pass variable to JSON without printing it as String

Time:08-10

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

CodePudding user response:

JSON is a text representation of some data structure.
Unless you write a JSON encoder (and you don't), you don't have any reason to produce JSON manually. Attempting to generate JSON using string concatenation fails if the variable strings (name in this case) contain quotes or backslash. Escaping them could produce valid results but the code becomes bloated and difficult to read without any gain.

JavaScript provides JSON.stringify for this purpose and this is the best way to generate JSON.
All you have to do is to build the data structure that you need to encode. In your example, the data structure is an object:

let name = "someName";
const original = {
  result: name,
  count: 42,
}

// encode
const json = JSON.stringify(original)

// decode
data = JSON.parse(json);

Use the debugger to see the values of json (it is a string) and data (it is an object).

CodePudding user response:

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!

  • Related