Append string before printing JSON data - javascript

I am getting JSON data from AJAX call. So, the JSON data has format like -
data[0].scores.sadness
So, the last part 'sadness' is one of the emotions. I have total 8 emotions. So, I don't want to print like -
data[0].scores.sadness, data[0].scores.anger
So, I have created one array with all 8 emotions -
var emotions = ['anger', 'contempt', 'disgust', 'fear', 'happiness', 'neutral', 'sadness', 'surprise'];
I am using Jquery to dynamically create few elements, in 'each' loop of jQuery I'm appending array to JSON response like this -
var emotionPer = $('<div>')
.text(data[0].scores + "." + emotions[i])
.appendTo(li);
The problem I'm facing is that, it is printing [object] [object].{name of emotion}
for example -
[object] [object].anger or [object] [object].sadness
Is there any way to interpret it like -
data[0].scores.anger
So , that I can get value of above.

.text(data[0].scores[emotions[i]])
You can access the value of a key inside an object by two ways:
obj.key
obj["key"]
Why your method didn't work:
var obj = {"name":"void", "on":"stackoverflow"};
var key = "on";
obj.on // stackoverflow
obj["on"] // stackoverflow
obj.key // Will be undefined
obj[key] // will be stackoverflow.
I hope it makes sense.

Related

Nan is being set in json model when trying to bind with odata response

I am creating a restructured json model in our sapui5 app wherein the data is being received from the odata response. I am using the json.setproperty() method.
if i try n access the value with following methods
var two = 2;
var test = "Count"
var three = test+two
alert(odata.results[0][three]);
correct value is being alerted with object notation as against Nan being alerted if dot notation was used.
so in a loop im trying to fill the content of the json
for(var i=0;i<=count-2;i++){
var z = "Count"+i;
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0].z);
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0][z]);
}
Nan is being returned when im trying with the dot notation and undefined is being returned with object notation.
if i hardcode the path i.e odata.results[0].Count4 i am getting the 4th element from the odata resp and getting set in all fields of the new json.
Please help me with the above.
Best regards
archit
You cannot access a multidimensional array like that. Instead try using this -
odata.results[0][odata.results[0].indexOf(three)]

Converting JSON to Usable object in Javascript

I have some JSON with two parameters expressed as
{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
I'm trying to get access to the "pushid" and the "count" as usable elements, either in an object, an array or a map, and am a little confused as to how to do that.
When I call JSON.parse(json) it returns undefined, and so I assume that it's already an object. However, when I try to use json[1] it returns the second character of the whole thing (which in this case is "). How do I make an object
var obj = {pushId: SOME_STRING, count: SOME_INT)?
Thanks in advance,
Considering:
var jsonString = '{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}';
You can do:
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.pushid); // 3533...
console.log(jsonObj['pushid']); // 3533...
console.log(jsonObj.count); // 1
console.log(jsonObj['count']); // 1
console.log(jsonObj[0]); // undefined
console.log(jsonObj[1]); // undefined
This is already an object so you don't have to parse it. {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
All you have to do is now assign it to what ever variable you want.
let data = {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1};
console.log("pushid : " + data["pushid"]);
pushid : 35336165333161382d646338302d346665302d626236312d303763313435663036656131
console.log("count : " + data["count"]);
count : 1
I mean, that number is too long for JS to represent in it's 64 bit floating point internal representation, but you can try to parse the base16 repr with
parseInt(obj.pushid, 16);

Adding an Individual JSON Object to an Array to Parse and Process

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

Can't parse my JSON into an object in javascript

I am working on a parser for a text file. I am trying to parse some JSON strings into objects so I can easily display some different values on a webapp page (using flask). I am passing the strings into my html page using jinja2, and trying to parse them objects in javascript.
function parseLine(x) {
var obj = JSON.parse(x);
document.write(obj.timestamp1);
}
I am getting this error:
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
in the console browser. I have found many stackoverflow questions with that error, but the suggestions do not fix my problem.
If I use a dummy string, surrounded by single quotes: '{"test": "1234"}' it works fine.
If I need to include anymore information I can.
Had similar issues but was able to solve it using this way using the
reviver parameter on JSON.parse()
var Person = {}
// an empty person object
//sample json object, can also be from a server
var sampleJson = {'name': 'Peter', 'age': "20"};
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person]
// the source is JSON.parse which take a string argument and a function reviver for the key value pair
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson),
function (k, v) {
//we return the key value pair for the json
return k, v
}
)
)
console.log(Person.name) //Peter
console.log(Person.age) // age

How to add data to a 2 dimensional array in javascript

I am trying to add values into an array but for some reason it is not working. I am new to JavaScript.
Here is my code:
eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray[index] = new Array('title' = value.title, 'date' = value.date[1]);
});
So basically I am pulling out some values from the json object and want to save them as key-value pairs in an array (multidimensional as each event has several values).
This array will later be sorted by date.
I am currently getting the following error:
ReferenceError: Left side of assignment is not a reference.
I am new to JavaScript and don't really understand whats wrong. Tried to look at some examples but still can't see a good example of creating two dimensional arrays with JavaScript (or objects, as everything in JS is an object) in a loop like this.
I would be very thankfull for any help or tips.
The cause of the error message is this:
'title' = value.title
That would mean that you are trying to assign a value to a literal string. The rest of the code (except from the other one just like it) is actually valid syntax, even if that is not what you are trying to do, so that's why you get the error message on that part of the code.
To have a collection of key-value pairs you would use an object instead of an array, and you can create it like this:
eventsArray[index] = { title: value.title, date: value.date[1] };
May be simplest one,
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function (index, value) {
eventsArray[index] = { 'title': value.title, 'date': value.date[1] };
});
It works if you change your code to:
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray.push({ title : value.title, date: value.date[1] });
});
You should use objects for this:
eventsArray[index] = {};
eventsArray[index].title = value.title;
eventsArray[index].date = value.date[1];
The problem you have is that you try to assign value.title value to String. Arrays in JS didn't work in that way. Also Arrays didn't support String keys, this is why you may need Object.
If your date property is TIMESTAMP for example you can sort it like:
eventsArray.sort( function( a, b ) {
return a.date - b.date;
});

Categories

Resources