undefined JSON values in Javascript error - javascript

I am reading through a JSON object, trying to loop through the text and create substrings of the text. It is, for some reason coming back as "cannot read property 'roles' of undefined." What am I missing?
// target language text
var text1 = obj[0].tgtLanguageSentences[0].text;
var strArry1 = [];
var colorArr1 = ["DarkSalmon", "ForestGreen", "Brown"];
for(var t=0; t<obj[0].tgtLanguageSentences[0].roles.length; t++)
{
// create variables representing substrings of the Source language Sentence
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
var tgt2 = text1.substring(obj[t].tgtLanguageSentences[t].roles[t].beginOffset,obj[t].tgtLanguageSentences[t].roles[t].endOffset);
var tgt3 =
text1.substring(obj[t].tgtLanguageSentences[t].roles[t].endOffset,obj[t].tgtLanguageSentences[t].text.length);
strArry.push('<h4>'+tgt1+'</h4>');
strArry.push('<h4>'+'<font color="'+colorArr1[i]+'">"'+tgt2+'</font>'+'</h4>');
if(i == obj[0].tgtLanguageSentences[0].roles[0].length-1)
{
strArry.push('<h4>'+tgt3+'</h4>');
}
text1 = s3;
}
Please see the JSON object in reference below:
[
{
"description": "",
"roles": [
{
"name": "thing commented on"
},
{
"name": "commentor"
}
],
"srcLanguageSentence": {
"roles": [
{
"beginOffset": 23,
"endOffset": 30,
"name": "thing commented on",
"text": "on them"
},
{
"beginOffset": 5,
"endOffset": 7,
"name": "commentor",
"text": "We"
}
],
"text": " `` We wo n't comment on them . '' ",
"verb": {
"beginOffset": 15,
"endOffset": 22,
"text": "comment"
}
},
"tgtLanguageSentences": [
{
"roles": [
{
"beginOffset": 1,
"endOffset": 31,
"name": "thing commented on",
"text": "Weitere Aspekte der Kommission"
},
{
"beginOffset": 44,
"endOffset": 47,
"name": "commentor",
"text": "ich"
},
{
"beginOffset": 48,
"endOffset": 55,
"name": "negation",
"text": "nicht ."
}
],
"text": " Weitere Aspekte der Kommission kommentiere ich nicht . ",
"verb": {
"beginOffset": -1,
"endOffset": -1,
"sense": "COMMENT, intransitive",
"text": "kommentieren"
}
}
],
"verb": "KOMMENTIEREN"
}
]

Change all of your references to
obj[t].tgtLanguageSentences[t].roles[t]
to
obj[0].tgtLanguageSentences[0].roles[t]

here is the problem:
In below snippet code you are looping through the role but in substring you passing obj[t].
As per above given JSON you have only one item in obj however in role you have more than 1 item.
for(var t=0; t<obj[0].tgtLanguageSentences[0].roles.length; t++)
{
// create variables representing substrings of the Source language Sentence
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
var tgt2 = text1.substring(obj[t].tgtLanguageSentences[t].roles[t].beginOffset,obj[t].tgtLanguageSentences[t].roles[t].endOffset);
var tgt3 =
text1.substring(obj[t].tgtLanguageSentences[t].roles[t].endOffset,obj[t].tgtLanguageSentences[t].text.length);
Answere is:
var tgt1 = text1.substring((obj[0].tgtLanguageSentences[0].roles[t].beginOffset - obj[0].tgtLanguageSentences[0].roles[t].beginOffset),(obj[0].tgtLanguageSentences[0].roles[t].beginOffset - 1));
Hope this will help you :)

Would be helpful to know, from debugging, which line is throwing the error. But it's probably this one:
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
Using t to index obj and tgtLAnguageSentences and roles is problematic based on your JSON object example. The loop will run 4 times based on t<obj[0].tgtLanguageSentences[0].roles.length.
When t = 1, for instance, you are trying to find a value at obj[1].tgtLanguageSentences[1].roles[1] if there is no object at obj[1].tgtLanguageSentences[1] then you will get "cannot read property 'roles' of undefined."

Related

assigning value from object without specifying the index

Let us say I have an object below and I have 2 variable. The length of the object is always fixed.
I wanted to assign the object index attribute value to variable A and object index 1 to variable B.
I can do like A = data[0].attributeValue; and B = data[1].attributeValue;
but is there a better and clean way to do this ? Thanks for any help or any idea. Appreciated.
#sample output
A = 'Test A'
B = 'Test B'
#sample variable
let A = '';
let B = '';
#sample object
data = [
{
"id": 13,
"type": "1",
"attributeValue": "Test A"
},
{
"id": 14,
"type": "2",
"attributeValue": "Test B"
}
]
You can read about Destructuring assignment but it won't help much .. well maybe a little:
data = [{
"id": 13,
"type": "1",
"attributeValue": "Test A"
},
{
"id": 14,
"type": "2",
"attributeValue": "Test B"
}
]
var [{attributeValue: A}, {attributeValue: B}] = data;
console.log(A, B)

I need to parse json array which consist of array inside object

Here is my JSON array which I need to parse using javascript code.
{
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
},
{
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
I am having an above json array and i need to display subject of each object from my json `which is inside individualticketlist here is my code.`
for(var i=0;i<jsonString.length;i++)
{
alert(a.individualTicketList[i].DueByDate);
}
Here's how to loop through it
let json = {
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
}, {
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
let arr = json["individualTicketList"]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].Subject);
console.log(arr[i].DueByDate);
//your other code here
}

How do I create a new object from an existing object in Javascript?

Working on JavaScript app and need help in creating a new object from response received from ajax call.
The output received is array of objects, sample format below:
{
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to swim",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
]
}
However, my component expects JS Object in the following format:
{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}
Is following approach correct, please suggest better approach if any
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
}
};
var gcalEvents = {};
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
console.log(content.items.length);
for (var index = 0; index < content.items.length; index++) {
var obj = content.items;
console.log(obj);
jsonObj.id = obj[index]["id"];
jsonObj.title = obj[index].summary;
jsonObj.start = obj[index].start.dateTime;
jsonObj.description = "";
console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
You could take a more functional approach with the following:
var parsed = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: item.start.dateTime
}
})
This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.
Take a look at this fuller example.
I have another way to convert this content.
Using Underscore.js to make the code more readable.
Here is the example:
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}, {
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}]
};
var result = _.map(content.items, function(item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The result as following:
[
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"title": "Learn to code",
"start": "2017-03-04T19:00:00+05:30",
"description": ""
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"title": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": "2017-03-07T11:30:00+05:30",
"description": ""
}
]
At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}]
};
var results = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(results);
var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
var obj = {};
console.log(obj);
obj["id"]=content.items[index].id;
obj["title"]=content.items[index].summary;
obj["start"]=content.items[index].start.dateTime;
obj["description"]="";
jsonObj.push(obj);
console.log(jsonObj);
//gcalEvents[index] = jsonObj;
}
This will give you jsonObj as your desired json object.
Hope this helps :)
Here's the fixed code:
One error was when you've listed the content items, a "]" was missing at the end.
The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values.
I've preferred to do the object define and assigning of the values in one go.
In order to have the output as an array, you just have to define the colection as an array and not am object eg: var gcalEvents = []
var content = {
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}
]
};
var gcalEvents = [];
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
//console.log(content.items.length);
for(var index=0; index < content.items.length; index++){
var obj = content.items[index];
//console.log(obj);
jsonObj = {
'id': obj["id"],
'title': obj.summary,
'start': obj.start.dateTime,
'description': ""
}
//console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);

Access nested members in JSON

I'm trying to access members in a json, however I am running into some trouble. Here is an example of one of the json objects, stored in var obj:
var fs = require('fs');
var obj = [
{
"_id": "52d7f816f96d7f6f31fbb680",
"regNum": "0361300035313000002",
"sd": "2013-01-01T00:00:00",
"pd": "2013-01-25T09:30:29Z",
"prd": "2012-12-18",
"p": 1395000000,
"pt": [
{
"name": name here",
"price": 1395000000,
"OKDP": {
"code": "5520109",
"name": "name here"
},
"sid": "25484812",
"sum": "1395000000",
"OKEI": {
"code": "796",
"name": "name two"
},
"quantity": "1"
}
],
"b": 0,
"c": 0,
"s": 0
}
];
I'm trying to access the sid and sum values, by doing the following:
var sid = [];
var sum = [];
obj.forEach(block => {
var sidOut = block.pt.sid;
var sumOut = block.pt.sum;
sid.push(sidOut);
sum.push(sumOut);
});
console.log(sid);
console.log(sum);
I tried the solution here, however, when I run these it gives me [ undefined ] errors.
Why am I unable to access this two values?
if you see your pt is an array of an object [{}] so you need to select which element you want to access so
var sidOut = block.pt[0].sid;
var sumOut = block.pt[0].sum;
should get you the right result

Is this valid json data?

The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!

Categories

Resources