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
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).
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!
👋 I need a little bit of help to understand JSON better.
When I stringify an array with class objects then parse it back, it looks like the array loses the class instance. Can I keep the class even after parse JSON data, and if can, how? And why does this happen?
Here is the code:
class Account {
constructor(site, login, pass) {
this.site = site,
this.login = login
this.pass = pass
}
}
const accounts = [
new Account("website1.com", "email1#gmail.com", "12345"),
new Account("website2.com", "email2#gmail.com", "23456")
]
console.log('BEFORE', accounts)
const string = JSON.stringify(accounts)
console.log(string)
const parseString = JSON.parse(string)
console.log('AFTER', parseString)
The console shows like this:
BEFORE (2) [Account, Account]
{string: "[{"site":"website1.com","login":"email1#gmail.com"….com","login":"email2#gmail.com","pass":"23456"}]"}
AFTER (2) [{…}, {…}]
To make things clear, is it possible to have [Account, Account] after JSON.parse()`?
Let me know if my explanation is not clear.
Thank you so much!
JSON has no support for types other than object, array, null, string, number and boolean.
If you kind of know what you can expect in your JSON, you can use a reviver function during parsing. For your example, this suffices:
JSON.parse(string, (k, v) => v.hasOwnProperty('site')
? new Account(v.site, v.login, v.pass)
: v);
JavaScript has two useful methods to deal with JSON-formatted content:
JSON.stringify() & JSON.parse(), which are useful to learn as a pair.
JSON.stringify() takes a JavaScript object and then transforms it into a JSON string.
JSON.parse() takes a JSON string and then transforms it into a JavaScript object.
What I understood from your question is that, you want your parsed JSON String converted into your Account Object Prototype. To achieve you could use the below code since JSON.parse() returns Javascript object which we explicitly need to convert to our custom object prototype ( i.e. Account in your case).
const string = JSON.stringify(accounts)
console.log(string);
const parseString = JSON.parse(string);
objectFromJson = function (parseString){
var temp = [];
for( var i = 0; i < parseString.length; i++) {
temp.push(new Account (parseString[i].site, parseString[i].login, parseString[i].pass));
}
return temp;
};
var accountArray = objectFromJson(parseString);
console.log('AFTER', accountArray);
I am having problem parsing JSON string into JS object .Please tell how to convert JavaScript object :
Object {d: "[{"worker_id":1,"worker_name":"Shivank"}]"}
into
Object { d: [{ "worker_id": 1, "worker_name": "Shivank" }] }
I have tried using
JSON.parse(data)
and
var dataFinal = JSON.stringify(data);
var d1 = eval('(' +dataFinal+ ')');
You have an object where one property value contains JSON so you only need to convert that value
Try
data.d= JSON.parse(data.d);
Assuming your data is as below, which d is having stringified json data
var data = {d: "[{\"worker_id\":1,\"worker_name\":\"Shivank\"}]"}
console.log(data);
You can parse JSON and assign to d key
data.d = JSON.parse(data.d)
console.log(data); // required output
I have a string with values i want to use. I'm parsing this string as an JSON object using $.parseJSON. However I'm having problems getting the actual values.
In this case I'm trying to get the value of the key "textarea1" which is "banana". What is the correct syntax for getting the values. I tried obj.texts.textarea1, but it didn't work.
The string looks like this:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
Script:
var oldVal = $.parseJSON(obj);
missing quote on \Apple
You access obj but need to access oldVal
you have nested arrays so you need array notation to get at them or flatten the arrays
You do not need jQuery and likely have not defined it. JSON.parse will work
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
console.log(oldVal[0].texts[0].textarea1)
If you want to access oldVal.texts.textarea1 you need to remove the array:
var obj = "{\"texts\":{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}}";
1st Option
You need not to change anything. Just fix your JSON in correct format.
You can use JsonLint to check your JSON is correct or not. Then Proceed further.
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
alert(oldVal[0].texts[0].textarea1)
2nd Option
If you want to get the result like obj.texts.textarea1 then you'll have to change your data as following.
Format Your JSON
Remove all [ and ] from your json.
then do.
var a = '{"texts": {"default": true,"bread-texts": false,"textarea1": "Banana","textarea2": "Kiwi","textarea3": "Apple","textarea4": "coffe","textarea5": "Tea","signature": true,"profile": "header","fontsize": "26","fontsize-headers": "10.5","fontcolor": "#0000","textfont": "header-large","textsub1": "Bold","font": "ICA%20Text","textsub": "Regular","textsize": "20","textsize-signature": "9.5","textsizesmall": "5.5","textsizesmall-placer": "2.75","vers-placer": "false","text-colored": "%23000000","s-all-customers": true,"new-customers": true,"undefined": ""} }';
var obj = JSON.parse(a);
Then
obj.texts.textarea1;
You've created array in your JSON so for that you need to do array accessing.
obj is of type string. You can not index it as object in the form obj.texts. You are parsing it using $.parseJSON, then use the object returned by that call:
var oldVal = $.parseJSON( obj );
var value = oldVal[0].texts[0].textarea1;
Your JSON is invalid.
At this place, you are missing a quote:
\"textarea3\":\Apple\" (escaped)
"textarea3":Apple" (unescaped)
JSON parsing will fail at this point.
After fixing this typo, I can easily access your JSON items this way:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
// using JSON.parse
document.body.innerHTML = JSON.parse(obj)[0].texts[0].textarea1;
// or using jQuery
document.body.innerHTML += $.parseJSON(obj)[0].texts[0].textarea1;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
the server response data is:
{virus: "[["0家":1907],["1~3家":618],["4~10家":436],["11~20家":1046],["20家以上":924]]"};
then I get this object value by key virus
how to convert this value to javascript array
var value = '"[["0家":1907],["1~3家":618],["4~10家":436],["11~20家":1046],["20家以上":924]]"';
Use JSON.parse(); to convert the XHR response to a JavaScript array.
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you use jQuery, :
var response = your data;
var obj = $.parseJSON(response);
alert(obj. virus); //true
alert(obj.count);