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.
Related
I'm trying to transform my object person to a JSON.
const person = new Object();
person.firstName = 'testFirstName';
person.lastName = 'testLastName';
var myJson = JSON.stringify(person);
console.log(myJson);
console.log(typeof myJson); // This returns me a string, not a JSON.
But when I try to print my supposed JSON and print the type of my element (myJson) I get is an string.
Someone can help me to understand this and can tell me how I could do this?
First you must know what are the differences between JSON & JS object. It is described in this answer link.
Normally when you fetch a JSON file it is in the string format, to use it as a object you have to parse the JSON file and then the string will be converted to object.
In your code by using the JSON.stringify(person) you already have converted the object into a JSON file.
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...
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.
I know how to access key value pair from JSON object but in my case, the resource bundle keys are mapped to values.
e.g.
var json = {"label.name.first":"foo","label.name.second":"bar"};
Here json.label.name.first doesn't give me "foo".
Can someone help me with this?
Due to using the period character (.) in the key name, you need to use the [] notation to access its value.
console.log( json['label.name.first'] );
Additionally, you have a JavaScript object, not JSON.
The difference between a JavaScript object or JSON is that JSON is always a string. Secondly, JavaScript objects don't require the same quote standards on the key names.
If you just consider the string below, then yes it can be considred JSON (this is why if you paste it into a JSON parser, it tells you it's valid JSON):
{"label.name.first":"foo","label.name.second":"bar"}
However, if you assign that directly to a JavaScript variable then you have a JavaScript object literal, not JSON. This is because JSON is also a valid JavaScript object/array literal when it is not contained in a string:
var obj = {"label.name.first":"foo","label.name.second":"bar"};
If you were to use it as a string, then it is JSON:
var json = '{"label.name.first":"foo","label.name.second":"bar"}';
// json is a string, so it's JSON
var obj = JSON.parse(json); // parse the JSON into an object
The confusion is quote common because the JSON format is very similar to the format of JavaScript object and array literals.
Do this:
json["label.name.first"]
However, I think you are misunderstanding the . notation.
And BTW your json isn't a JSON, it is a javascript object and not its notation.
It's json["label.name.first"] that would get you "foo". Since your property's name contains characters that cannot be used in variable names.
If you're expecting to access these properties using the syntax json.label.name.first then your JSON needs to be:
var json = {
"label":{
"name":{
"first":"foo",
"second":"bar"
}
}
}
This is not right way to create object, you should create one like this.
var json={"label":{"name":{"first":"foo","second":"bar"}}};
it will also work as json string
I have a JSON object in following format which I need to convert to pure String...as 0000-0000-0000-0000-000 so I was wondering how I can do this in Javascript?
{ KEY: "0000-0000-0000-0000-000" }
try this (where data is the data returned from the API call)
var tokenString = data.KEY;
alert(tokenString);
try
console.log(obj)
to view it in the browser debugger console
or
JSON.stringify(obj);
I would recommend using
JSON.stringify()
Extra info on this method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Your object is not JSON when it's in JavaScript, it's JavaScript code. The string version you're asking for is JSON (JavaScript Object Notation). This is why you can do things in JavaScript that you cannot do in JSON, like representing functions and binary data.
The function you're looking for to turn your JavaScript object into JSON is JSON.stringify() which you would use like this:
var obj = { }; //put your object here
console.log(JSON.stringify(obj)); //output the JSON version of your object
Also, the object in your question is not valid JSON or JS. In either scenario you'd need to put quotes around the 0000-0000-0000-0000-0000 and give it a value. The following is valid JSON:
{ "0000-0000-0000-0000-0000": null }
Store your response in one variable and then do
response.KEY