Json Javascript String Syntax error when parsing an array - javascript

I have the following code javascript code
var tasksPlayed = [];
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);
this gives an error
SyntaxError: JSON.parse
Im not sure why, if I do a .toSource() on the objects I get
keyValue:"[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true]"})
Any ideas where I might be going wrong

I don't get this error when I run the code, but the thing with the null values is that tasksPlayed is an array, so when you set tasksPlayed[90] = true;, then it automatically fills all positions from 0 to 89 with null. Try using a plain object instead of an array:
var tasksPlayed = {};
tasksPlayed[90] = true;
var json = JSON.stringify(tasksPlayed);
var output = JSON.parse(json);

Related

JSON Parse Error "TypeError: undefined is not an object" "[object Object]

I been trying to JSONParse this rest api, but haven't had any luck. Would anyone be able to see why I keep getting either [object Object] or undefined error?
<div id="store_1_name"></div>
<div id="owner_1_name"></div>
<div id="friend_1_name"></div>
var raw_data_string = '{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}';
var data = JSON.parse(raw_data_string);
for (var i in data) {
ParseUpdate(data[i].house, data[i].condo, data[i].apartment);
}
function ParseUpdate(house, condo, aparment) {
var house = data[i].house;
var condo = data[i].condo;
var apartment = data[i].buy.apartment;
}
document.getElementById("store_1_name").innerHTML = data[0].house;
document.getElementById("owner_1_name").innerHTML = data[0].condo;
document.getElementById("friend_1_name").innerHTML = data[0].apartment;
Thanks all!
You are doing so many things wrong here. 1st, the JSON string is invalid. 2nd, You're trying to access wrong elements inside the for loop. 3rd, data[i].buy.apartment doesn't exist if you're also accessing data[i].house in the same loop as they are inside the same object which is buy. 4th, you're trying to show JSON object in the innerHTML of a div where you should access the string value you want to show or stringify the whole object.
var raw_data_string = '{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}]}';
var data = JSON.parse(raw_data_string)[2][0]['buy'];
for (var i in data) {
ParseUpdate(data[i].house, data[i].condo, data[i].apartment);
}
function ParseUpdate(house, condo, aparment) {
var house = data[i].house;
var condo = data[i].condo;
var apartment = data[i].apartment;
}
document.getElementById("store_1_name").innerHTML = data[0].house;
document.getElementById("owner_1_name").innerHTML = JSON.stringify(data[0].condo);
document.getElementById("friend_1_name").innerHTML = JSON.stringify(data[0].apartment);
<div id="store_1_name"></div>
<div id="owner_1_name"></div>
<div id="friend_1_name"></div>
Your json string invalid
Check your data struct and correct the loop again (for)
apartment is an object but you show it same string
document.getElementById("friend_1_name").innerHTML = data[0].apartment; will not work
var raw_data_string =
'{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}]}';
var data = JSON.parse(raw_data_string);
console.log(data);
There were some missing closing brackets in the raw_data_string. I would suggest JSON Formatter & Validator.

Javascript object undefined issue

I'm a little stumped here. Can someone tell me why this works:
var selectedAttrs = {"mattress_size_variation":{"displayName":"Mattress Size","value":"King","displayValue":"King"},"mattress_feel_variation":{"displayName":"Mattress Feel","value":"Soft","displayValue":"Soft"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
//Returns "King"
But this does not and throws an error?
var selectedAttrs = {"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}};
var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();
TypeError: Cannot read property "value" from undefined
What is the difference and how should I get the value from the last one? I'm assuming I need to do some sort of check since one works and the other does not.
There's a untrimmed space in your second JSON so you have to access that property using square brackets:
selectedAttributes['mattress_size_variation ']
var selectedAttrs = '{"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}}'
var selectedAttributes = JSON.parse(selectedAttrs);
console.log(selectedAttributes['mattress_size_variation '].value);

Get element in array (json format)

how can i get the first "id_miembro" for example of this:
{"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]}
I've tried with other ways but nothing, thanks.
Parsing a JSON string in javascript can be done with JSON.parse(). For your JSON you can do this to get the id_miembro of the first item in the list.
var json = '{"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]}';
var obj = JSON.parse(json);
var actividades = obj.actividades;
var first = actividades[0];
var id_miembro = first.id_miembro;
I broke it down into seperate variables so it's easier to follow which line does what.
If your data is alread a javascript object you can skip the first two lines and just do this
var obj = {"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]};
var actividades = obj.actividades;
var first = actividades[0];
var id_miembro = first.id_miembro;

AngularJS Convert Array to JSON

I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?
That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;

parsing a JSON fails with missing element in javascript

I am trying to use Youtube's Gdata JSON response in javascript. My code iterates through the playlist and extract the item data.but for few videos the rating is not there which throws
"TypeError: item.gd$rating is undefined"
is there a way to check before accessing the element.
this is the code with with i fetch the json response.
var avgrating = item['gd$rating']['average'];
var maxrating = item['gd$rating']['max'];
var minrating = item['gd$rating']['min'];
var numRaters = item['gd$rating']['numRaters'];
One way you can just do to avoid error is
var rating = item['gd$rating'] || {}; // If it is undefined default it to empty object
var avgrating = rating['average']; //now if it is not present it will just give undefoned as value
var maxrating = irating['max'];
var minrating = rating['min'];
var numRaters = rating['numRaters'];
Or explicitly check:
var rating = item['gd$rating'], avgrating, maxrating;
if(rating)
{
avgrating = rating['average'];
maxrating =rating['max'];
...
}
Note that in the if condition we are checking for truthiness of the expression so, anything other than undefined, null, "", false, 0 will be treated as true and will go into the condition. But here you are sure that it will be either an object or nothing so you can rely on this check.

Categories

Resources