How do I attach JSON Stringify to a javascript variable - javascript

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?

As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).

You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array

.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()

You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

Related

Javascript. Access variable values from javascript Object

I want to access a variable value of a Javascript object. The below image is a result of a console.log: console.log(variable).
I tried:
variable[0] -> returns undefined
Also tried converting using JSON.stringify -> shows '[]' on the console
Here's the screenshot of the value I want to get:
Assuming the array variable is the array of two objects, to get the string "tag1", you should try variable[0].name.

Javascript - key and value in array

I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));

JSON / JavaScript get object keys

I'm extracting data from as follows -
The above function returns data in the below format -
[Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, volume=859}, Object { date=Date, value=123, volume=1284}, Object { date=Date, value=113, volume=1382}, Object { date=Date, value=129, volume=1353}]
I would like to obtain the list of keys only as a simple array.(Parsing the first object in the array is enough to get this as all other objects have the same keys) In case of the above output, I would like the simple array to look as ["date","value","volume"]
I tried JSON.stringify & then parse but it still doesn't work.
Also, how could I convert the whole array obtained from the chart into a simple array please?
I'm visualizing an output of the below type -
[{'date':'whatever', 'value':126, 'volume':911},
{'date':'whatever', 'value':136, 'volume':1005},
{'date':'whatever', 'value':125, 'volume':720}]
If the question doesn't make sense, please let me know. I'll see how best I could re-word.
Use Object.keys() function. Here in the response from function you get an array. Use that to get the list of keys.
var data = getChartData('param')
Object.keys(data[0]);

Get value from json "undefined" what I have wrong?

I have this string:
[
{"id":"001",
"name":"Charlie"},
{"id":"002",
"name":"Ellie"},
]
Them, I save this string in a variable and I parse it:
function parseJSON(string){
var mylovelyJSON = JSON.stringify(string);
alert(mylovelyJSON[id]);
}
When I make my alert, I get and "undefined", I also tried with "mylovelyJSON.id", And I get the same.
Could not be a Json? I get this string from an php array.
There are many things wrong here
Your JSON is invalid
You have an extra , just before the end of the array that you need to remove
You need to parse
JSON.stringify converts a JavaScript data structure into a string of JSON.
You need to go the other way and use JSON.parse.
Square-bracket notation takes strings
mylovelyJSON[id] takes the value of id (which is undeclared so, in this case, would throw a reference error) and gets the property with the name that is the same as that value.
You need either mylovelyJSON["id"] or mylovelyJSON.id
You have an array
Your JSON consists of an array of objects, not a single object.
You need to get an object out of the array before you can access properties on it.
mylovelyJSON[0]["id"]
var json_text = '[{"id":"001","name":"Charlie"},{"id":"002","name":"Ellie"}]';
parseJSON(json_text);
function parseJSON(string){
var result_of_parsing_json = JSON.parse(string);
document.body.appendChild(
document.createTextNode(result_of_parsing_json[0]["id"])
);
}
Two things are wrong here
Your array ends with a comma, which isn't valid json
You are converting a string to javascript, and stringify does the opposite of that.
So something like this might work:
var id = 0;
function parseJSON(string){
var mylovelyJSON = JSON.parse(string);
alert(mylovelyJSON[id]);
}
Note I am assuming that id is a global variable...

How can I convert my Json object to a string?

I have an asynchronous function that returns remote json and stores it in a variable. After that, I try to use JSON.stringify on that variable and display the contents in an alert message to make sure they're a string instead of [object].[object],[object]. Here's the code:
Jsonvar = result.shows;
var jsonstr=JSON.stringify(Jsonvar)
alert(jsonstr + "yay");
It's not displaying anything. If you need even more code let me know.
If you have another method to convert the object to a string, let me know.
JSON.stringify(JSON_OBJECT) will convert a valid JSON object to string.
jsFiddle - check this example
Note : verify if result.shows is a valid JSON object.

Categories