Json error of undefine when using for loop - json

im learning JSON and encounter a problem when looping JSON.
This is my JSON response
{
"success": 1,
"category": [{
"id": "1",
"category": "Editorial",
"created_at": "2019-11-05 18:10:31",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "2",
"category": "Sports",
"created_at": "2019-11-05 19:25:50",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "3",
"category": "Health",
"created_at": "2019-11-05 19:27:23",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "4",
"category": "Food",
"created_at": "2019-11-05 19:39:17",
"firstname": "abc",
"lastname": "xyz"
}]}
and this is my loop
for(var i = 0; i <= jsonData.category.length; i++){
console.log(jsonData.category[i]['firstname']);}
it does print in console but it gives me this error
Cannot read property 'firstname' of undefined
at Object.success

Use < instead of <=. Otherwise you reach an undefined index.
for(var i = 0; i < jsonData.category.length; i++){
console.log(jsonData.category[i]['firstname']);
}

Related

Merge 2 nested JSON objects with add or update fields in nodejs

Here are the JSON in play:
origJSON
{
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"_id": "564d098e2e59e72412e4d795",
"purl": "3",
"firstName": "Jon",
"finalGrade": "B",
"template": "User.html",
"sensitive": "{"ssn":\"123-00-6789\",\"acc\":\"987654300\",\"password\":\"zxcvbn!\"}"
}
newJSON
{
"purl": "3",
"firstName": "Jon",
"sensitive": {
"password": "qazwx",
"phone": "1234567890"
}
}
merged origJSON
{
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"_id": "564d098e2e59e72412e4d795",
"purl": "3",
"firstName": "Jon",
"finalGrade": "B",
"template": "User.html",
"sensitive": {
"password": "qazwx",
"phone": "1234567890"
}
}
desired origJSON
{
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"_id": "564d098e2e59e72412e4d795",
"purl": "3",
"firstName": "Jon",
"finalGrade": "B",
"template": "User.html",
"sensitive": {
"ssn": "123-00-6789",
"acc": "987654300",
"password": "qazwx",
"phone": "1234567890"
}
}
Here is the code to I've got:
for(var key in newJSON) origJSON[key]=newJSON[key];
Any help to get the nested objects updated instead of replaced ?
Use the lodash library's _.merge() method to achieve the desired result. Here are various examples of the available methods but the _.merge() is the one you are after:
var origJSON = {
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"_id": "564d098e2e59e72412e4d795",
"purl": "3",
"firstName": "Jon",
"finalGrade": "B",
"template": "User.html",
"sensitive": {"ssn":"123-00-6789","acc":"987654300","password":"zxcvbn!"}
};
var newJSON = {
"purl": "3",
"firstName": "Jon",
"sensitive": {
"password": "qazwx",
"phone": "1234567890"
}
};
Using _.assign():
var assigned = _.clone(newJSON);
_.assign(assigned, origJSON);
console.log("assign:", JSON.stringify(assigned, null, 4));
Output
assign: {
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"purl": "3",
"firstName": "Jon",
"sensitive": {
"ssn": "123-00-6789",
"acc": "987654300",
"password": "zxcvbn!"
},
"_id": "564d098e2e59e72412e4d795",
"finalGrade": "B",
"template": "User.html"
}
Using _.merge()
var merged = _.clone(newJSON);
_.merge(merged, origJSON);
console.log("merge:", JSON.stringify(merged, null, 4));
Output
merge: {
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"purl": "3",
"firstName": "Jon",
"sensitive": {
"password": "zxcvbn!",
"phone": "1234567890",
"ssn": "123-00-6789",
"acc": "987654300"
},
"_id": "564d098e2e59e72412e4d795",
"finalGrade": "B",
"template": "User.html"
}
Using _.defaults()
var defaulted = _.clone(newJSON);
_.defaults(defaulted, origJSON);
console.log("defaults:", JSON.stringify(defaulted, null, 4));
Output
defaults: {
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"purl": "3",
"firstName": "Jon",
"sensitive": {
"password": "zxcvbn!",
"phone": "1234567890",
"ssn": "123-00-6789",
"acc": "987654300"
},
"_id": "564d098e2e59e72412e4d795",
"finalGrade": "B",
"template": "User.html"
}
Check the demo below.
var origJSON = {
"2014": {
"grade": "A-",
"className": "Geography 101"
},
"_id": "564d098e2e59e72412e4d795",
"purl": "3",
"firstName": "Jon",
"finalGrade": "B",
"template": "User.html",
"sensitive": {"ssn":"123-00-6789","acc":"987654300","password":"zxcvbn!"}
};
var newJSON = {
"purl": "3",
"firstName": "Jon",
"sensitive": {
"password": "qazwx",
"phone": "1234567890"
}
};
var assigned = _.clone(newJSON);
_.assign(assigned, origJSON);
console.log("assign:", assigned);
var merged = _.clone(newJSON);
_.merge(merged, origJSON);
console.log("merge:", merged);
var defaulted = _.clone(newJSON);
_.defaults(defaulted, origJSON);
console.log("defaults:", defaulted);
pre.innerHTML = "assign: " + JSON.stringify(assigned, null, 4) + "</br>merge: " + JSON.stringify(merged, null, 4) + "</br>defaults: "+ JSON.stringify(defaulted, null, 4);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<pre id="pre"></pre>
There are plenty of options to do this with utility libraries like lodash and also ES6 destructuring (maybe).
But, imo, the most maintainable way and while using one of those, would be using an object factory. Assuming that the object structure will be the same all over... It's easier to wrap you head around, than libraries you don't know or complex clone/merge/dedupe algorithms. My bet is also that JS engines optimize factories better.
function outputFactory(input_1, input_2){
// some conditions and/ or data handling here
var desiredProperty = (input_1.someProperty >= input_2.someProperty) ? input_1.someProperty : input_2.someProperty;
return {
desiredProperty: desiredProperty
}
}
var merged = outputFactory({someProperty:1}, {someProperty:2})
console.log(merged)
Hope this gives you an option.

angularJS JSON parsing

I am new to angularJS and trying to parse the data and display it on a page.
{
"count": 13,
"status": 200,
"statusMessage": "OK",
"userContact": [
{
"user": {
"id": 1,
"firstName": "test",
"lastName": "test",
"universityId": 1,
"email": "test#harbingergroup.com",
"password": "",
"phoneNo": "1234567890",
"gender": "M",
"userType": 1,
"medicalComments": "",
"dob": "2015-02-22",
"universityAffiliation": 1,
"cityId": "1"
},
"userContactList": {
"count": 2,
"status": 200,
"statusMessage": "OK",
"contact": [
{
"id": 2,
"userId": 1,
"firstName": "test",
"lastName": "user",
"phoneNo": "9876543210",
"email": "test#example.com"
},
{
"id": 24,
"userId": 1,
"firstName": "first1",
"lastName": "last1",
"phoneNo": "9876543210",
"email": "test#example.com"
}
]
}
}]
}
this is my JSON data.What i am trying is :
<tr ng-repeat="studentDetails in studentProfileData">
studentDetails.status for getting status and studentDetails.userContacts.firstName for first name
but I am not getting the data. What is wrong here?
Assuming that studentProfileData contains a list of users (userContact):
studentDetails.user.firstName
will contain "test"

Jmeter JSON Path Assertion

Below is my JSON response data, I need to do assertion using the below response. I tried in many ways to write JSON path & Expected Value. Always assertion fails. What I want is please help to write the path and expected value for the below data
{
"statusCode": 200,
"statusMessage": "Success",
"errorMessage": "",
"responseData": {
"id": 15,
"userName": "partner#tarento.com",
"firstName": "tarento",
"lastName": "test1",
"phoneNumber": "1234567812",
"email": "partner#tarento.com",
"password": "",
"city": "",
"agentList": [
{
"id": 37,
"userName": "Rahul.antonyRaj#tarento.com",
"firstName": "Sanjay",
"lastName": "rahul",
"phoneNumber": "7411269480",
"email": "Rahul.antonyRaj#tarento.com",
"password": "",
"active": true
},
{
"id": 68,
"userName": "jinesh.sumedhan#tareto.com",
"firstName": "jinesh",
"lastName": "sumedhan",
"phoneNumber": "9400993826",
"email": "jinesh.sumedhan#tareto.com",
"password": "",
"active": true
},
{
"id": 108,
"userName": "a.sanjayrahul#gmail.com",
"firstName": "Rahul",
"lastName": "Antony",
"phoneNumber": "9994590241",
"email": "a.sanjayrahul#gmail.com",
"password": "",
"active": true
},
{
"id": 304,
"userName": "a.sanjayrajish#gmail.com",
"firstName": "Agent",
"lastName": "Agent",
"phoneNumber": "9025699716",
"email": "a.sanjayrajish#gmail.com",
"password": "",
"active": true
}
],
"roleName": "admin",
"sessionKey": "435tnerLt9813942160478oDse46345635#1",
"partner": {
"id": 1,
"name": "Tarento",
"cityList": [
"bangalore",
"mumbai"
],
"phone": "1234567812",
"url": ""
},
"isActive": true,
"isDeleted": false,
"roleId": 1,
"countryCode": "",
"tags": [
{
"tagId": 1,
"name": "all",
"description": "this is default tag of all driver."
},
{
"tagId": 2,
"name": "airport",
"description": ""
},
{
"tagId": 3,
"name": "street",
"description": "any text message"
},
{
"tagId": 255,
"name": "night",
"description": "night"
}
]
}
}
I received the following response
For start following JSONPath Assertion will test your statusCode
$.statusCode
put 200 to Expected Value of JSONPath Assertion.
This one is for userName
$.responseData.userName
Easy, isn't it? See Parsing JSON guide for more useful examples and how-tos.
I found the JSR223 Assertion with script language javascript to be the easiest. at least if you have knowledge in java and javascript. And no need to add any plugins.
My working code in detail:
var json = JSON.parse(SampleResult.getResponseDataAsString());
if (json.statusCode != 200) {
AssertionResult.setFailureMessage(""
+ json.statusCode
+ " " + json.statusMessage
+ " " + json.errorMessage);
AssertionResult.setFailure(true);
}
I personally prefer to use BSF PostProcessor in coupling with Groovy language. Example of how to parse JSON with Groovy you can find here how to parse json using groovy

How do i check my Json

I'm using Titanium Appcelerator to develop an Android application..I getting an error while using 'ACS JSON' .. I trying to use posts query, But i getting different kinds of array ..i need to check is whether the string is available or not before access..
For Example:
"response": {
"posts": [
{
"id": "52e7800340b4b0aa134",
"title": "test",
"created_at": "2014-01-28T10:01:39+0000",
"updated_at": "2014-01-30T11:59:54+0000",
"content": "#hi all",
"reviews_count": 3,
"ratings_count": 3,
"ratings_average": 3.67,
"ratings_summary": {
"5": 1,
"3": 2
},
"user": {
"id": "52e5e87f08a3e70b3309c3e3",
"first_name": "aa",
"last_name": "ss",
"created_at": "2014-01-27T05:02:55+0000",
"updated_at": "2014-01-30T11:58:49+0000",
"external_accounts": [
],
"confirmed_at": "2014-01-27T05:02:55+0000",
"username": "ss",
"role": "a",
"admin": "false"
},
"custom_fields": {
"postedby": "aa",
}
},
{
"id": "52e7908a3e70b3d0a9614",
"title": "bb",
"tags": [
"sdf",
],
"created_at": "2014-01-28T11:46:00+0000",
"updated_at": "2014-01-30T11:09:17+0000",
"content": "#hi# #kWh v #sdf",
"user": {
"id": "52e5e87f08a3e70b3309c3e3",
"first_name": "bb",
"last_name": "bbc",
"created_at": "2014-01-27T05:02:55+0000",
"updated_at": "2014-01-30T11:58:49+0000",
"external_accounts": [
],
"confirmed_at": "2014-01-27T05:02:55+0000",
"username": "b",
"role": "b",
"admin": "false"
},
"custom_fields": {
"postedby": "b"
}
},
See I getting *ratings_count* in my first post..while trying access this inside for loop i getting error..
Now i need to check is whether the string is available or not before access..!
In titanium you can check anything whether it exist or not by using if statment.You can do this
if(ratingcount){
//Do here whatever you want to do
}
Thanks
Try:
for (var i in response.posts) {
post = response.posts[i];
if (post.ratings_count) {
/* Do operations for post with ratings */
} else {
/* Do operations for post without ratings */
}
}
This is pretty basic operation in JavaScript, so before you dive deeper into Titanium it's good to catch up with plain JS before.

How can i change the Json Data Format?

i have the following Json Data with following format...
var oData = [
{
"0":
{
"firstname": "aaa",
"lastname": "zzz",
"Email": "aaa#test.com"
},
"1":
{
"firstname": "bbb",
"lastname": "yyy",
"Email": "bbb#test.com"
},
"2":
{
"firstname": "ccc",
"lastname": "www",
"Email": "ccc#test.com"
}
}];
Can we convert to the following format ??
var rData = [
{
"firstname": "aaa",
"lastname": "zzz",
"Email": "aaa#test.com"
},
{
"firstname": "bbb",
"lastname": "yyy",
"Email": "bbb#test.com"
},
{
"firstname": "ccc",
"lastname": "www",
"Email": "ccc#test.com"
}];
var oData = [{
"0":
{
"firstname": "aaa",
"lastname": "zzz",
"Email": "aaa#test.com"
},
"1":
{
"firstname": "bbb",
"lastname": "yyy",
"Email": "bbb#test.com"
},
"2":
{
"firstname": "ccc",
"lastname": "www",
"Email": "ccc#test.com"
}
}],
data = oData[0],
rData = [];
JSON.stringify( data, function( key, value ) {
rData.push( value );
});
console.log( rData );