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

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...

Related

How do I attach JSON Stringify to a javascript 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.

How to create an object from a string containing initializer

I'm reading Object initializer strings from a database but can't see any easy way to turn them back into objects.
For example, given the following string, how would you turn it into an object?
var initializer = "{type: car, colour: red, engine: 2.0L}";
I ended up decoding them by just looping through piece by piece but felt that there must be a better way.
since your data isn't quoted there won't be a difference between datatypes everything must be parsed as string.
Instead of trying to parse this shit i would try to create valid parsable data in the first place.
In the unlikely case that, instead of returning JSON from the server as you should, you do end up parsing this yourself, here's how you might do that:
initializer
.replace(/^\{|\}$/g, '') // remove {} at beginning and end
.split(',') // break apart into key: val pairs
.reduce(function(result, keyval) { // build object
var parts = keyval.split(':').map(''.trim);
result[parts[0]] = parts[1];
return result;
}, {});
Of course, you'd probably want to add a bunch of bullet-proofing to that.
If you're using Underscore, you could use its ability to create an object from an array of [key, val] pairs:
_.object(initializer
.replace((/^\{|\}$/g, '')
.split(',')
.map(function(keyval) {
return keyval.split(':').map(''.trim);
})
);

Access JSON object to get Resource Bundle key/value pair

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

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.

Serialize a javascript array

I have observed that in php you can encode an array and the resulting json does not carry the square brackets.However,in my javascript array,
var arrCars = new Array("Toyota", "Mercedes", "BMW");
var jsonStr = JSON.stringify(arrCars);
alert(jsonStr);
i keep getting the square brackets.I have also noticed that if i use json stringfy,
var foo = {};
foo.bar = "new property";
foo.baz = 3;
var JSONfoo = JSON.stringify(foo);
i get the json without the square just like i wanted.What must i do to my array to do away with the brackets?.
There's a difference between an array ([]) and an object ({}) in javascript. Your first example uses an array. Your second example uses an object. The main difference is that when you have an array ([]) the index can only be a zero based integer. Whereas an object can have property names that are strings.
The correct JSON for the array in your first example is ["Toyota","Mercedes","BMW"], and the correct JSON for the object in your second example is either {"bar":"new property","baz":3} or {"baz":3,"bar":"new property"}.
A JSON string contains either an object or an array, so it always has either curly brackets {} or square brackets [].
If you get anything else, the result is not correct. If you expect anything else, your expectation is wrong.
If you want the curly brackets instead of the square brackets, you have to serialise an object, not an array.
Not sure why you don't want brackets, since brackets are the normal way to make an array literal (as opposed to using the Array() function, as you do, which is way old-school)
If you want the JSON without the brackets, such as if you are building a bigger JSON string or something, you can use something like this:
function jsonifyArrayWithoutBrackets(a) {
var output = [];
for (var i=0; i<a.length; i++)
output.push(JSON.stringify(a[i]));
return output.join(',');
}
Or, obviously, just trim the brackets off after using a single call to JSON.stringify().

Categories