How to update the whole array of objects using Put http request with a json raw body? - json

I have a json Array something like below and I want to make an update to the whole list without passing by a specefic ID.
List before update
[ { id:"1", name : "name_1" }, { id:"2", name : "name_2" } ]
Wanted list after update
[ { id:"1", name : "name_3" }, { id:"2", name : "name_4" } ]
I tried using PUT request and passing the target list in a json raw body, but it always return "404 not found"
I tried it with Postman but it returns the same error. Is it possible to do like so ?

Related

Trying to get values form a list inside a JSON respons

My goal is to loop over a JSON response, grab two values, and build out an API call to load information into a POST to create a policy I am building.
To start out on this, I am trying to get two values from a JSON response to assign as variables to build the POST call, which will be the second step to this. As each different "id" and "name" key is assigned, I would like to build out a JSON payload and send the POST calls one at a time. The keys "id" and "name" occurs multiple times in the response payload and I am having issues capturing the two keys.
JSON response
data = {
"data":[
{
"id":"02caf2be-3245-4d3d",
"name":"ORA-FIN-ACTG",
"description":"Oracle",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"03af2f46-fad6-41a1",
"name":"NBCMAINFRAME",
"description":"Network",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"0649628b-0e3b-48df",
"name":"CAMS",
"description":"Customer",
"links":{
"web":"https://com/",
"api":"https://com/"
}
},
{
"id":"069d4bcf-3e50-4105",
"name":"SHAREPOINTSITES",
"description":"Sharepoint",
"links":{
"web":"https://com/",
"api":"https://com/"
}
}
],
"took":0.013,
"requestId":"1f364470"
}
I have tried various "for loops" to grab the data. Here is one of the loops below:
data = json.loads(data)
data[0]['data'][0]['name']
for item in range(len(data)):
print(data[item]['data'][0]['name'])
I have also tried reading it as a dictionary:
for data_dict in data:
for key, value in data_dict.items():
team.append(key)
id.append(value)
print('name = ', team)
print('id = ', id)
I am also getting KeyError's and TypeError: the JSON object must be str, bytes or bytearray, not 'dict'.
Any help is appreciated.
FYI, this is the payload I am wanting to populate with the "name" and "id" values:
data= {
"type":"alert",
"description":"policy",
"enabled":"true",
"filter":{
"type":"match-any-condition",
"conditions":[
{
"field":"extra-properties",
"key":"alertOwner",
"operation":"equals",
"expectedValue":name
}
]
},
"ignoreOriginalResponders": "true",
"ignoreOriginalTags": "true",
"continue": "true",
"name": str(name) + " Policy",
"message":"{{message}}",
"responders":[{"type":"team","id":id}],
"alias":"{{alias}}",
"tags":["{{tags}}"],
"alertDescription":"{{description}}"
}
The JSON response which you have given is already a dictionary so no need to use json.loads for that. The multiple item list is actually nested under the data key. So you could just simply iterate through the array of items like this:
for item in data["data"]:
print("{} : {}".format(item["id"],item["name"]))
This is the output:
02caf2be-3245-4d3d : ORA-FIN-ACTG
03af2f46-fad6-41a1 : NBCMAINFRAME
0649628b-0e3b-48df : CAMS
069d4bcf-3e50-4105 : SHAREPOINTSITE

Retrieve values from JSON response, and create a drop-down

I'm trying to get each of of the values inside my JSON file but when I run my API I get [Object Object] instead of what is inside the JSON.
This is my API request:
getAllvalues(): Observable<string[]> {
return this.http
.get<string[]>(this.Url + 'api');
}
my component.ts
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
console.log (this.slots)
});
Example of my JSON response:
[
{
"AB": "http:"
},
{
"DE": "http:"
},
{
"CE": "http:"
},
{
"HI": "http:"
}
]
How can I get the value inside the JSON, and create a dropdown box with each of them?
Your example JSON is a pretty bad example: each object in the array in the JSON should have at least somewhat matching key names. In your case, the keys are "AB", "DE", "CE", "HI" - all different, which is quite uncommon in real-life. A more realistic JSON response would have matching key names, e.g.:
[
{
"id": "1",
"description": "Some description"
},
{
"id": "2",
"description": "Another description"
}
]
Now to answer your questions:
You are getting [Object Object] because you are trying to use an entire object as a literal value. Instead, you should access the individual keys/values of an object. For example: console.log(slots[0].id) - this should output 1.
Also, as indicated in the comments, replace Observable<string[]> with Observable<any[]> and get<string[]> with get<any[]>.
To create a drop-down in Angular, in your component template you can try this, assuming your slots value is the JSON above:
<select *ngIf="slots" name="slots">
<option *ngFor="let slot of slots" value="slot.id">{{ slot.description }}</option>
</select>
Also, to print the entire object to console in a readable form, instead of just console.log(this.slots);, you can try console.log(JSON.stringify(this.slots));
As mentioned in the comments above it is not ideal to have json like you have, my assumption is you might want to log keys instead of values, since value is same for all the objects in array. In that case you might want to try something like this.
1. Add any[] instead string[].
2.Add nested for loop to console.log your object array.
getAllvalues(): Observable<string[]> {
return this.http
.get<any[]>(this.Url + 'api');
}
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
for(let i in this.slots)
{
let currentObj = this.slots[i]; // example of first in array { AB : "http:"}
for ( let z in currentObj )
{
if(currentObj[z]=== "http:") // we are trying to find key instead value
{
console.log(z); // it will log AB, DE, CE, HI ..
}
}
}
});

Best Schema for a Data List in JSON for RestFul API to use in Angular

I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.

Jmeter - How to validate portions of response json

I have the following json:
{
"content":
[
{
"id":1,
"userId":2,
"storeId":8,
"userFirstName":"Max",
"userLastName":"Mustermann",
"city":"Berlin",
"spendQuantity":100,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":23,
"id":"432",
"rate":"1.9345345",
"symbol":"USD",
"rank":2,
}
},
{
"id":2,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Berlin",
"spendQuantity":1000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":3,
"id":"234",
"rate":"1.922222245345",
"symbol":"USD",
"rank":2,
}
},
{
"id":3,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Munich",
"spendQuantity":3000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":2332,
"id":"234",
"rate":"3.234234",
"symbol":"USD",
"rank":2,
}
},
{
"id":4,
"userId":2,
"storeId":3,
"userFirstName":"Newman",
"userLastName":"Mustermann",
"city":"Essen",
"spendQuantity":4000,
"paymentStatus":"UNPAID",
"userBalanceStatus":null,
"rateObject":
{
"identifier":234,
"id":"234",
"rate":"333.234234",
"symbol":"USD",
"rank":2,
}
}
}
But I need to verify it partially - Only the fields in the nested jsons where city is Berlin or Essen, but without the rateObject (I don't need to verify this part). With other words I need to verify nested jsons with ids- 1,2,4 - all fields, without the information in rateObject.
Partial Answer and Suggestion:
We can apply the filter condition in the JSON Query to fetch the matched details.
For Example: To get the id of the mentioned city,
JSON Query:
$.content[?(#.city=="Berlin" || #.city=="Essen")].id
Output:
[
1,
2,
4
]
Similarly, you can assert all the required fields using the filter JSON Query.
JMeter JSON Extractor will provide only one value at a time.So, you can either add some logic to verify all the occurrences or multiple verification can be added by specifying the id index ( $.content[?(#.city=="Berlin" || #.city=="Essen")].id[0] --> It gives the first occurrence Id )
If you want to validate multiple fields,then you can write the customized script in Bean Shell Post Processor.(Refer the below link and you will get some idea)
Extracting JSON Response using Bean Shell Postprocessor
If you are using the Bean Shell Post Processor, then required java jar files should be placed in JMeter ClassPath( Folder: apache-jmeter-4.0\lib\ext)

Salesforce JSON Nested Self-Related Objects?

Looks like I need some help here. Salesforce documentation and multiple google searches not gave me an answer.
Problem description:
I'm trying to insert (POST) nested self-related records using REST with JSON, but every time this error appears:
{
"message": "Cannot deserialize instance of <unknown> from FIELD_NAME value records or request may be missing a required field",
"errorCode": "JSON_PARSER_ERROR"
}
JSON:
{
"records" :[{
"attributes" : {"type" : "Test_Obj1__c", "referenceId" : "ref1"},
"name" : "integr parent",
"Test_Obj1__r" : {
"records" : [{
"attributes" : {"type" : "Test_Obj1__c", "referenceId" : "ref2"},
"name" : "integr child"
}]
}
}]
}
Request:
https://mySandboxInstance.com/services/data/v37.0/composite/tree/Test_Obj1__c/
Authorization: OAuth security_token
Content-Type: application/json
So, as you can see Test_Obj1__c is self-related and Child Relationship Name is "Test_Obj1".
I've tested with different self-related objects - it gives same result.
If I'm changing Test_Obj1__r to relation with different child object - it works fine.
Is there any way to insert nested self-related objects through one REST request?