I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:
{
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
Now i am finding a way to get the data from the object user. How can i do it with javascript?
Complementing #arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:
data['user'][0]['user_id']
this is useful because you can have a 'class' array and then do things like:
['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));
then you can filter only some classes or do more advanced stuff
When you have the data (in example it's in data) use the dot notation to get the node with the user.
The user is an array, so use [] to access a single element, e.g. [0]
var data = {
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
console.log( data.user[0].user_id )
I prefer use square brackets like this :
$jsonObject["user"][0]["user_id"]
but you can use the dot like this :
data.user[0].user_id
is the same thing.
If you want check if property exist you can do it :
if(typeof $jsonObject["user"] !== 'undefined'){
//do domethings as typeof $jsonObject["user"][0]["user_id"]
}
If you want get property dinamically you can do it :
const strId = "id";
const strName = "name";
//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];
but there isn't very pretty.
Related
I'm writing tests in POSTMAN against a POST API request by sending JSON body data of the following format:
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"activities" : null
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe"
}
}
I get Response for the request in similar format with some added details:
{
"status": "Success",
"message": "Created new 'Student' record",
"correlationCode": "Z848640-261354",
"type": {
"id": 51247,
"name": "Student",
"slug": "student",
"application": {
"name": "Willow University"
}
},
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe",
"name": "11206"
}
}
Now i want to achieve two things here:
1. Verify each key in response body does not have null value. Please note i'm sending one key with value as null and it is not returned in response.
2. The value sent in request body for each key is value returned by same key in response body. For instance if "name" key has value "Amber Joseph" then response key "name" also returns "Amber Joseph". But i want to do it for each key. Also Keys can defer everytime for instance i might or might not send it with "name" key hence i need a generic solution that applies to whatever key value pairs i send.
I'm able to loop through by using:
let jsonData = pm.response.json();
let dKey = Object.keys(jsonData);
let dValue = Object.values(jsonData);
for(var i = 0; i < dV.length; i++ ){
pm.expect(dV[i]).to.not.eql(null);
}
But this does not check nested key value pair individually.I specially want to check each key value pair inside the "data" object. Any help would be appreciated.
Thanks
You can grab the JSON data from the request like this:
const requestJson = JSON.parse(pm.request.body.raw);
(This assumes you're using a RAW body in Postman.)
Then, you can compare the response's data fields with the original request's data fields:
const requestJson = JSON.parse(pm.request.body.raw);
const responseJson = pm.response.json();
for (const [reqKey, reqValue] of Object.entries(requestJson.data)) {
pm.expect(responseJson.data[reqKey]).to.eql(requestJson.data[reqKey]);
}
From there, you can add whatever checks you want to do on the rest of the response.
Given the following object, how is the email property referenced? I've been trying variations of getresponse.partner[0].email to no avail.
{"getresponse":{"$":{"unpagedCount":"10"},"partner":[{"$":{"id":"p1e","type":"content","name":"myname","status":"active","email":"me#here.com","peopleIds":"9","personIds":"9"},"ketchup":[""]}]}}
thanks in advance!
-b
$ is a valid property/variable name in Javascript. Just use it like any other property name:
let $$$ = {
"getresponse": {
"$": {
"unpagedCount": "10"
},
"partner": [{
"$": {
"id": "p1e",
"type": "content",
"name": "myname",
"status": "active",
"email": "me#here.com",
"peopleIds": "9",
"personIds": "9"
},
"ketchup": [""]
}]
}
}
console.log($$$.getresponse.partner[0].$.email);
Just access it as a normal key in any JS object via getresponse.partner[0].$.email. Note that $ is a legal variable identifier name, as you can check in this other post.
var obj = {"getresponse":{"$":{"unpagedCount":"10"},"partner":[{"$":{"id":"p1e","type":"content","name":"myname","status":"active","email":"me#here.com","peopleIds":"9","personIds":"9"},"ketchup":[""]}]}}
var email = obj.getresponse.partner[0].$.email
console.log(email)
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I am Just trying to learn RethinkDB.I am little Bit Confused That how to delete an single Object in an array,What is the Exact query I have to use if i have to delete this Object
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
}
from whoLikedIt Array
My data
{
"comments": [ ],
"id": "c242c74d-03d9-4963-9a22-4779facb8192" ,
.....
"views": 0 ,
"whoLikedIt": [
{
"name": "Vignesh Warar" ,
"username": "d97bf210-c42d-11e6-b783-07b5fe048705"
},
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
},
]
.....
}
My Try
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(
{whoLikedIt:r.row('whoLikedIt').filter({username:"B97bf210-c4d2d-11e6-b783-07b5fev048705"}).delete()}
)
Throws Me a error
e: Cannot nest writes or meta ops in stream operations. Use FOR_EACH instead in:
You want:
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(function(row) {
return {whoLikedIt: row('whoLikedIt').filter(function(obj) {
return obj('username').ne("B97bf210-c4d2d-11e6-b783-07b5fev048705");
})};
})
I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place