Getting [object Object] in javascript when I want the value - javascript

I've looked at some similar questions, but not seeing exactly what I am doing wrong. I am passing a dict from a .py file to a file that uses javascript.
I know that the javascript file is getting my dict like this:
var numbersFromServer = [{"a": "45", "b": "22", "c": "7"}];
So, when I try something like this:
var numbersFromServer = {{ numbers_list|safe }};
var NumbersViewModel = function() {
var self = this;
theNumbers = [];
for (var key in numbersFromServer) {
theNumbers.push(numbersFromServer[key]);
}
self.num_display = ko.observableArray(theNumbers);
}
ko.applyBindings(new NumbersViewModel());
I am getting [object Object] when I want to get the actual values (45, 22, 7).
Can someone please point me in the right direction?
A fiddle that shows what I am trying to do: http://jsfiddle.net/Znk3q/1/

You have object in array so to get element you shoud
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}

It looks like you have an array containing one object. To access it you need to
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}

Related

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

Add objects to JSON

I have a JSON that looks like this:
{
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
}
When I add an object to it:
addObj[obj.length] = saveobject;
the previous content gehts replaced.
When I make an array out of it and push the object:
addObj = [loadedJSON];
addObj.push(saveObj);
I get this after the first
[Object]
after the second so fare so good
[Object, Object]
and after the third it gets messed up
[Array(2), Object]
What do I miss?
I hope some one can help with this?
The way I hoped it would look like is this.
[Object, Object, Object, ...and so on]
EDIT
to be More specific
when I add a new Object I load the JSON file in a variable and then I try to add the new Object.
Which works for the first two objects but the third one is added to the first object so that I got this result.
[Array(2), Object]
I dont want it nested like this! But how do I get it like this?
[Object, Object, Object].
EDIT
So eventually you all were right I just mixed up the array when i loaded it the second time every thing is fine now thank for pointing me in the right direction.
on the first time:
var a= [];
var b= {};
b= 'some things';
a.push(b);
and wenn a.length != null
b= 'the rest';
a.push(b);
and now everything is just as expected!
As far as I understand it, this has nothing to do with JSON.
It seems you want to have an array storing successive instances of a given object (that happens to have been encoded in JSON at some point, but for the problem at hand we could not care less).
First, create a sorage array.
Then push each new instance into it.
var storage = []; // your storage array, initially empty
// ....
while (some_guy_wants_to_send_me_something ())
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
EDIT:
If you use a button:
var storage = []; // your storage array, initially empty
// ....
function add_whatever_object ()
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
// HTML
<button type="button" onclick='add_whatever_object();'>
I still don't see where the catch is.
check the if it is an array:
Array.isArray(loadedJSON) //true
do this:
loadedJSON.push(saveObj);
if it was not an array push it to an array:
var myarray = [];
myarray.push(loadedJSON);
an then push your other object:
myarray.push(saveObj);
an so on:
myarray.push(otherObj);
I am a little unclear on what you actually want, but based on a little speculation I was able to write the following code for you. I hope this will solve your problem.
var a ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var b ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var c ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var ObjArr = [];
ObjArr.push(a);
ObjArr.push(b);
ObjArr.push(c);
console.log(ObjArr);
Here is the fiddle to it => http://jsfiddle.net/rB3Un/

Getting json data from a nested array

I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.
var translator = function () {
for (var i = 0; i < result.length; i++)
{
//Construct URI
var source =
'https://www.googleapis.com/language/translate/v2?' +
'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
'source=en&' +
'target=fr&' +
'q=' +
result[i][1]; //looping over an array, no problem there
//Receive response from server
var to_Translate =new XMLHttpRequest();
to_Translate.open("GET",source,false);
to_Translate.send();
var translated = to_Translate.responseText;
JSON.parse(translated);
translated = translated.data.translations[0].translatedText;
console.log(translated);
}
};
translator();
Where
console.log(translated);
yields
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
My question is: how can i access the value of translatedText? I've tried:
translated.data.translations[0].translatedText;
But it doesn't seem to work. When I console.log this i get
Uncaught TypeError: Cannot read property 'translations' of undefined
translator
(anonymous function)
Let me know what you guys think!
That is just text you have to parse it with
JSON.parse(translated)
so you could access it with, for example, translated.data
UPDATE
The error you are getting means that translated.data is undefined, you have to assign the parse to a variable, otherwise it will never work, it doesn't modify it in place
var translated = JSON.parse(to_Translate.responseText);
Yes, Use
translated.data.translations[0].translatedText;
Hope it will work fine.
So close!
translated.data.translations[0].translatedText;
translations is an array of objects, and you want the translatedText property of the first element in the array.
UPDATE:
Just to confirm the output of to_Translate.responseText is a string containing:
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
So you should be able to do:
var translated = to_Translate.responseText,
parsed = JSON.parse(translated),
text = parsed.data.translations[0].translatedText;
console.log(text);

Encoding Javascript Object to Json string

I want to encode a Javascript object into a JSON string and I am having considerable difficulties.
The Object looks something like this
new_tweets[k]['tweet_id'] = 98745521;
new_tweets[k]['user_id'] = 54875;
new_tweets[k]['data']['in_reply_to_screen_name'] = "other_user";
new_tweets[k]['data']['text'] = "tweet text";
I want to get this into a JSON string to put it into an ajax request.
{'k':{'tweet_id':98745521,'user_id':54875, 'data':{...}}}
you get the picture. No matter what I do, it just doesn't work. All the JSON encoders like json2 and such produce
[]
Well, that does not help me. Basically I would like to have something like the php encodejson function.
Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
You can use JSON.stringify like:
JSON.stringify(new_tweets);

Using variable keys to access values in JavaScript objects

The code:
function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}
The object data:
{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}
The problem:
alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".
alert(bsID); properly displays "A5A50000".
alert(data.bsID[0].time); reports "data.bsID is undefined".
alert(data[bsID][0].time); reports "data[bsID] is undefined".
I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.
You can access object properties by dot notation or by bracket notation.
var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi
When you have a dynamic value, you have to use the latter:
var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi
So what you actually want is:
alert(data[bsID][0].time);
EDIT:
Not sure what you're doing wrong, but this is working for me on Firebug's console:
var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);
In Javascript, you can use either object or array-style notation to look up an attribute. The following are equivalent:
data.A5A50000
data['A5A50000']
With the second syntax, you can use a variable in place of an object string:
data[bsID][0]
I experienced the same problem with a nested JSON API-response:
[
{
"bj_code": "2019",
"BJ_PERIODE": [
{
"nummer": 1
},
{
"nummer": 2
}
]
}
]
I could evaluate:
pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);
But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:
const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);

Categories

Resources