-2

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
Loizos Vasileiou
  • 674
  • 10
  • 37
  • Just quote the value correctly `const json = '{"result":"'+name+'", "count":42}';` or use template literals `const json = \`{"result":"${name}", "count":42}\`;` OR parse the original and add the value: `obj["result"] = name` – mplungjan Aug 10 '22 at 11:46
  • There's no need to escape the `"` inside a string which uses `'`. Also, consider using a template literal instead? `JSON.parse(\`{"result": "${name}", "count":42}'\`)`. But then you're better off using `JSON.stringify` – evolutionxbox Aug 10 '22 at 11:52
  • 2
    Do not attempt to generate JSON by string concatenation. It does not work if `name` contains characters that are special for JSON (quotes, backslash). – axiac Aug 10 '22 at 11:52

2 Answers2

0

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 the method JSON.stringify() to produce a JSON from any data and this is the best way to generate JSONs.
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);
console.log(json);

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

Running the code snippet here in page is not relevant because the output that it produces looks similar for both calls of console.log().
Run the code using Node.js or run it in the browser's console to see the values of json (it is a string) and data (it is an object).

axiac
  • 68,258
  • 9
  • 99
  • 134
-2

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!

  • 1
    _"JSON is quite literally a JavaScript object"_ - no it's not. It's a textual notation that uses similar syntax to JS for simplicity. – evolutionxbox Aug 10 '22 at 12:07
  • A JavaScript Object Notation, is a javascript object that follows certain formatting rules and syntax, it's not _similar to_, but it is derived from – Christian Smith Mantas Aug 10 '22 at 12:11
  • No that's simply not true. It is a lightweight data-interchange format. https://www.json.org/json-en.html - It is not a JavaScript object. – evolutionxbox Aug 10 '22 at 12:16
  • The code is correct but the first paragraph of text is plain wrong. JSON **is** text (a string), not object. Its purpose is to be persisted or transported and it cannot be easily manipulated as is. The JSON needs to be decoded to get back a data structure equivalent to the data structure used to generate it. Usually the data structure used to build a JSON is an object and this probably fuels the confusion of many developers that think that JSON is an object. It is not. – axiac Aug 10 '22 at 19:42