Gravity Forms Web API - Field Names with fullstops issue - json

I'm using the Web API to download form entries into an offline system and having an issue with my JSON parser with some of the form field IDs. For example I receive an entry with fields like this:
{
"response": {
"entries": [
{
"3.3": "Henry",
"3.6": "Ford",
"3.2": "",
"3.4": "",
"status": "active",
"transaction_id": null,
"transaction_type": null,
The period/fullstop in the field ID is throwing out my JSON parser which uses the period/fullstop as the separator ($.response.entries[0].3). Is there a way to change the period/fullstops to underscores of have the API return the name of the field instead like it does for "transaction_type" etc?

A hacky solution if you can't change how the data is coming from the API would be to pre-parse it yourself. You can do something like this using a simple string replace:
var data = {
"response": {
"entries": [
{
"3.3": "Henry",
"3.6": "Ford",
"3.2": "",
"3.4": "",
"status": "active",
"transaction_id": null,
"transaction_type": null,
}
]
}
}
data = JSON.stringify(data)
data = data.replace(/\./g, '_');
data = JSON.parse(data)
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Related

getting data from an array of objects inside array JSON data

I have trouble taking data from an API set. The body if viewed in Postman / Insomnia is as follows
{
"responses": {
"log": [
{
"id": 123,
"date": "2022-01-01T01:12:12.000Z",
"type": "online",
"details": [{
"detailId": "123-1",
"note": "success",
}]
},
{
"id": 124,
"date": "2022-01-01T01:12:12.000Z",
"type": "offline",
"details": [{
"detailId": "123-2",
"note": "failed",
}]
}
]
}
}
I want to take all data from log, as well from details. I used
adapt(item: any) {
return {
id: item.id,
date: item.date,
details: {
detailId: item.details.detailId,
note: item.details.note,
},
};
}
this returns id and date just fine. I also have a query to filter it based on type (online or offline), basically adding &type= into the API. It works for the online, but it returns detailId is undefined for offline (I used the same body, adapter and API minus the query for both data)
details is an array of object if you want to adapt it you need to do it iteratively.
adapt(item: any) {
const details = item.details.map(d => {detailId: d.id, note: d.note, …});
return {
id: item.id,
date: item.date,
details
};
}
Found the answer, apparently to make sure that I can get every value is to add ? after the [0], so it should be
details: {
detailId: item.details[0]?.detailId,
note: item.details[0]?.note,
},

How to create a dynamic request in Jmeter

I have a response from an API
[{
"userSourceMeta": {
"userId": "sss#gmail.com",
"source": "BOX",
"organisationId": 1,
"emailId": "sss#gmail.com",
"sourceUserId": "15548727375",
"accessToken": null,
"refreshToken": null,
"lastCursorPosition": null,
"lastAccessTime": 1626025027228,
"name": "John",
"createdAt": 1622444279509
},
"connectionStatus": null}, {
"userSourceMeta": {
"userId": "test#gmail.com",
"source": "ONEDRIVE",
"organisationId": 1,
"emailId": "sss#outlook.com",
"sourceUserId": "3969b928a1a28f34",
"accessToken": null,
"refreshToken": null,
"lastCursorPosition": null,
"lastAccessTime": 1626025027228,
"name": "sss ddd",
"createdAt": 1624262423446
},
"connectionStatus": null}]
I have to use two parameters in the successive request(source,sourceUserId) . This is a dynamic request it can be varied 3, 4,5 ..etc.
Next API request.
{
"Answer": "My name is xyz",
"queryChannel": "WEB_APP",
"timeZone": "Asia/Calcutta",
"sourceFilterInfo": [{
"sourceUserId": "15548727375",
"source": "BOX"
}, {
"sourceUserId": "3969b928a1a28f34",
"source": "ONEDRIVE"
}],
"contextIds": []
}
Please provide a solution to send a dynamic request with the previous API response.
I used regular expression extractor to store values. But how to send it in a request.
Add JSR223 PostProcessor as a child of the request which returns the above JSON and put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def sourceFilterInfo = []
response.each { entry ->
def user = [sourceUserId: entry['userSourceMeta'].sourceUserId, source: entry['userSourceMeta'].source]
sourceFilterInfo.add(user)
}
def payload = [:]
payload.put('Answer', 'My name is xyz')
payload.put('queryChannel', 'WEB_APP')
payload.put('timeZone', 'Asia/Calcutta')
payload.put('sourceFilterInfo', sourceFilterInfo)
payload.put('contextIds', [])
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
That's it, now you should be able to refer the generated request as ${payload} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

How do i get a specific data from responseBody on postman

I'm trying to set an environment variable using the following:
var data = JSON.parse(responseBody);
pm.environment.set("petId", data.id);
And this is what is in my response:
{
"id": 9222999990497629102,
"category": {
"id": 0,
"name": "dog"
},
"name": "Brutus",
"photoUrls": [
"http://placeimg.com/640/480"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
But somehow my environment looks like this:
"petId": "9222999990497629000"
I don't where from where I'm getting these last zeros on my variable.
pm.environment.set("petId", JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id);
As the id is a big int greator than MAX_SAFE_Integer , the response will be rounded when parsed as JSON. It is a javascript behavior.
You can enclose it with double quotes. After that extract that id.
now if you want to convert id to number use BigInt
let id = JSON.parse(pm.response.text().replace(/"id":[\s]*([\d]+),/,'"id":"$1",')).id
id = BigInt(id)
console.log(id)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})

How to parse a key value nested in another key whose name is not know in python?

I'd like to access the value of extract key that is nested in the pages key
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "sample",
"to": "Sample"
}
],
"pages": {
"23895873": {
"pageid": 23895873,
"ns": 0,
"title": "Sample",
"extract": "<p><b>Sample</b> or <b>samples</b> may refer to:</p>\n<p></p>\n"
}
}
}
}
I am creating a wikipedia bot that will print the summary (value of the key "extract") . But the problem is that the "pageid" value keeps on changing with the search result . How can I do this?
I tried using json:
import json
import requests
wikiReq = requests.get("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=&titles=sample&format=json")
jsonResult = wikiReq.json()
result = jsonResult["query"]["pages"][""]["extract"]
print(json.dumps(result , indent = 4))
You can do
for i in jsonResult["query"]["pages"]:
result = jsonResult["query"]["pages"][i]["extract"]
Assuming there is just one item in there it will always work