How to get a value from nested JSON data - javascript

I am trying to get a value from the nested JSON data below. Specifically, the payments captures id value 0TA12948FV40723B is the value I need.
I try using the following codes to retrieve the value.
details.purchase_units.payments.captures.id
details.purchase_units.payments[0].captures.id
But I keep getting a console.log Error: "Order could not be captured"
JSON DATA
{
"create_time":"2019-02-19T05:06:52Z",
"update_time":"2019-02-19T05:06:52Z",
"id":"3HB96413YD922272B",
"intent":"CAPTURE",
"status":"COMPLETED",
"payer":{
"email_address":"a#yandex.com",
"payer_id":"WEJUPTK4U53E9",
"address":{
"address_line_1":"1 Main St",
"admin_area_2":"San Jose",
"admin_area_1":"CA",
"postal_code":"95131",
"country_code":"US"
},
"name":{
"given_name":"a",
"surname":"som"
},
"phone":{
"phone_number":{
"national_number":"408-214-8270"
}
}
},
"purchase_units":[{
"reference_id":"default",
"amount":{
"value":"1.01",
"currency_code":"USD"
},
"payee":{
"email_address":"gr-facilitator#yandex.com",
"merchant_id":"MSOIGVMKKWAMA"
},
"shipping":{
"name":{
"full_name":"Mr T"
},
"address":{
"address_line_1":"1234 Main St.",
"address_line_2":"Unit 1",
"admin_area_2":"Chicago",
"admin_area_1":"IL",
"postal_code":"60652","country_code":"US"
}
},
"payments":{
"captures":[{
"status":"COMPLETED",
"id":"0TA12948FV40723B",
"final_capture":true,
"create_time":"2019-02-20T05:06:52Z",
"update_time":"2019-02-20T05:06:52Z",
"amount":{
"value":"1.01","currency_code":"USD"
},
"seller_protection":{
"status":"ELIGIBLE",
"dispute_categories":[
"ITEM_NOT_RECEIVED",
"UNAUTHORIZED_TRANSACTION"
]}
}
]}
}]
}

Since purchase_units and captures are arrays:
details.purchase_units[0].payments.captures[0].id

captures key have objects in side an array. so you can't simply fetch like
details.purchase_units.payments[0].captures.id
you have to give the position of the captures or loop the array only you can do parsing
details.purchase_units.payments[0].captures[0].id

If you add your json as object using the chrome console you will be able to do what I did in in the image below. purchase_unit is an array so you need to access it using the index.

In case if you want to capture all the IDs in an array, you can use wild card:
details.purchase_units[*].payments.captures[*].id
This will parse complete payload for specified path and collect all the IDs in an array.

Related

Cloud firestore: Update field values in nested array object with dot notation

Please help me solve this, I would like to update the fields using dot notation, using set() but each time I run with the below implementation. I have the fields added to firestore as e.g studentInfo.0.course.0.courseId instead of updating the already existing ones.
Json sample as it sits in firestore
"schoolId": "school123",
"studentInfo": [
{
"studentId": "studentI23",
"regDate": "2020-04-18",
"course": [
{
"courseId": "cs123",
"regDate": "2020-05-28",
"status": "COMPLETED"
}
]
}
],
"registered":"yes"
}
Code logic
const query = firestore.collection('users').where('registered', '==', 'yes')
const students = await query.get()
students.forEach(student => {
firestore.doc(student.ref.path).set({
'studentInfo.0.studentId': '345','studentInfo.0.course.0.courseId': '555'
}, { merge: true })
})
On the docs https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects I can only find updating nested objects but not nested array objects.
It is indeed not possible to update a single element in an array using dot notation, or otherwise. To update an array you'll need to:
Read the document
Get the current value of the array from it
Determine the new array contents
Write the entire updated array back to the database.
The only alternative array operations are array-union and array-remove, which add and remove unique elements to/from the array - essentially treating it as a mathematical set. But since you are looking to update an existing element, these operations are of no use here.
Also see:
Firestore Update single item in an array field
Firestore update specific element in array
How to update an "array of objects" with Firestore?
There is no direct way to update the as stated in the article. You can either run a transaction to get the latest array value and then updating the array with the final array value. That would be as below:
await firestore.runTransaction((transaction: Transaction) => {
const students: Array<Students> = firestore
.collection("users")
.where("registered", "==", "yes");
students.forEach((student) => {
const firebaseDoc = firestore.doc(student.ref.path);
transaction.set(
firebaseDoc,
{
"studentInfo.0.studentId": "345",
"studentInfo.0.course.0.courseId": "555",
},
{ merge: true }
);
});
});
Inside transaction I am getting the array first and then updating each values as per my need. This will make the whole operation atomic so the issues mentioned in the article will not come.
Alternatively, you can also model your firestore database as below
"schoolId": "school123",
"studentInfo": {
"studentI23": {
"studentId": "studentI23",
"regDate": "2020-04-18",
"course": [
{
"courseId": "cs123",
"regDate": "2020-05-28",
"status": "COMPLETED"
}
]
}
},
"registered":"yes"
}
Above I have changed the array to map, since in map you can update the each field based on dot notation fields(doc), hence. you can achieve your end result. This solution will avoid any transaction query and will be faster

Searching for multiple facetsValues in Algolia

I have an array of Facet Values that I need to gather from an Algolia Indices.
For example, these are: "Beds", "Occupancy". and "Floor".
At the moment, i've got the below code which will go to my Algolia Table, grab me all of the possible values for each of the above but I have to do a query into Algolia for each one. This results in 3 network calls to Algolia.
index.searchForFacetValues(
{
facetName: val,
facetQuery: "",
maxFacetHits: 100,
query: "2019"
},
function(err, content) {
return content
})
Is there a way that I can get all the facet values for "Beds", "Occupancy". and "Floor" in a single query resulting in only one network call?
Also, i'm using https://www.algolia.com/doc/api-client/getting-started/install/javascript/
You can use an empty search and specify which facets you want to receive values for:
client.search({
query: '',
facets: ['Beds', 'Occupancy', 'Floor'],
attributesToRetrieve: [], // a little optimisation for response transfer speed
});
The response will contain something like this:
{
"facets": {
"Beds": {
"2": 1245,
"4": 893,
...
},
"Floor": {
...
},
...
}
}
So the first level of keys in facets are your facet names, and within each nested facet object you have one key/value per facet value/hits count.
If you don't know in advance the list of facet names you want to get, use facets: '*' in your query parameters.

json response handling from soap wsdl

below is the response from soapWSDL in json.i need to print the pname,pjob .i can able to print "client":"http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessSubList", using alert(result.responseJSON.Envelope.Body.processResponse.client); but cant able to print sublist.pname which displays undefined error
{
"Envelope":{
"Body":{
"processResponse":{
"client":"http:\/\/xmlns.oracle.com\/InternetMobile\/AbsManagement\/BPELProcessSubList",
"subList":[
{
"personid":"30979",
"pjob":"Senior Consultant",
"pname":"Imad El Kustomany"
},
{
"personid":"30980",
"pjob":"Senior Consultant",
"pname":"Abdul Rahman Zaky"
}
],
"xmlns":"http:\/\/xmlns.oracle.com\/InternetMobile\/AbsManagement\/BPELProcessSubList"
}
},
}
Try result.responseJSON.Envelope.Body.processResponse.subList[0].pname and result.responseJSON.Envelope.Body.processResponse.subList[1].pname. subList is an array so you can loop and use index as well
Sublist is an array so you need:
alert(result.responseJSON.Envelope.Body.processResponse.client.subList[0].pname);
or if you want to display pnames of all items
result.responseJSON.Envelope.Body.processResponse.client.subList.forEach(function(el){
alert(el.pname);
});

Accessing data from json in Angularjs

I have a JSON object Like this-
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "
[{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"w\",\"ansYesOrNo\":false,\"ansDetails\":\"\"},{\"question\":\"Q2\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"ed\",\"ansYesOrNo\":false,\"ansDetails\":\"\"}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
I need to access the 1st question of questions.Please i am not able to access it like this alert(obj.questions[0].question);
Here is a jsFiddle Link-LINK to Fiddle
The main problem is that the questions array inside the object, It is not an array. Is a Array convert to string, you must parse the questions to get the respective Json object with the data.
Here is your fiddle updated: http://jsfiddle.net/marduke182/w02ck9uw/1/
And the part of code important:
var questonObj = JSON.parse($scope.a[0].questions);
Use fromJson method this way:
angular.fromJson(a[0].questions)[0].question

How to filter the json data using Underscore

I am new to Underscore. I have a json array which is pasted below. If I want to filter the below array based on developed field having "yes" as value. How can I do using Underscore.js. Currently I am iterating over the content of array and manually selecting the objects and populating in into another array. Is there a better way to do using Underscore?
{
"content": [
{
"stateName": "Karnataka",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Kerala",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Tamilnadu",
"population": 1023213213213,
"developd": "yes"
},
{
"stateName": "Bsadasd",
"population": 1023213213213,
"developed": "no"
}
]
}
Not sure if I'm missing something here but the obvious underscore function is filter:
var developedStates = _.filter(data.content, function(state){
return state.developed == 'yes';
});
You can filter an array on its properties by using _.where :
where _.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the
key-value pairs listed in properties.
which leads to
var filtered = _.where(data.content, {developed: "yes"});
and a demo http://jsfiddle.net/nikoshr/NExZC/
As far as I know, underscore doesn't have a way to help you with this task. You can do this without using underscore with a native Javascript method called select:
var filteredArray = originalArray.select(function(item, index) {
return item.developed == "yes"; // Include this item if it has a proper value
});
Note that the select method is only available in browsers that support EcmaScript 5 specifications, so for older browsers you will need some supporting library like es5-shim.

Categories