Refer screenshot:
{
"urn:pearson:work:876fa82c-9ad7-49c3-80c9-02d3b4c84312": {
"id": "urn:pearson:work:876fa82c-9ad7-49c3-80c9-02d3b4c84312",
"type": "element-authoredtext",
"schema": "http://schemas.pearson.com/wip-authoring/element/1",
"elementdata": {
This is not working:
var jsonData = pm.response.json();
pm.environment.set("id", jsonData.id);
var jsonData = pm.response.json();
pm.environment.set("id", jsonData["urn:pearson:work:876fa82c-9ad7-49c3-80c9-02d3b4c84312"].id);
JsonData will have the full response , Id is inside "urn:pearson:work:876fa82c-9ad7-49c3-80c9-02d3b4c84312" field.
As it has special character you should call it as json[key] , then the next key which is id could be called as json.id, as it doesn't have any special characters
Update
for dynamic value use:
var jsonData = pm.response.json();
pm.environment.set("id", jsonData[Object.keys(jsonData)[0]].id);
The above will select the first property , but if you want to make sure it is the right one then use array.find():
let jsonData = pm.response.json();
let prop = Object.keys(jsonData)
prop = prop.find(element => element.includes("urn:pearson:work"))
pm.environment.set("id", jsonData[prop].id);
Related
I'm attempting to merge two PDF files from Google Drive via ConvertAPI with the following code. Both pdf1 and pdf2 are file objects.
function mergePDFs(pdf1,pdf2){
const formData = ""
formData['Files[0]'] = pdf1.getBlob();
formData['Files[1]'] = pdf2.getBlob();
Logger.log(formData['Files[0]']);
Logger.log(formData);
endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=XXXXXXXXXXXXX&StoreFile=true"
var options = {
'method' : 'post',
'payload' : formData,
'muteHttpExceptions': true
};
Logger.log(UrlFetchApp.fetch(endpoint,options));
}
To which I receive the following error code:
{"Code":4000,"Message":"Parameter validation error.","InvalidParameters":{"Files":["Files array item count must be greater than 0."]}}
It should be noted both Logger.log() statement come up empty. It appears to me that assignments of pdf1 and pdf2 to formData['Files[index]'] are not
I have modified the following lines considerably as I'm not familiar with this syntax, but it was referenced on another Stack Overflow post.
formData['Files[0]'] = pdf1.getBlob();
formData['Files[1]'] = pdf2.getBlob();
I'm also finding that the declaration of formData is inconsequential regardless of whether it's declared as an array or as a string.
Lastly, the pertinent documentation from ConvertAPI says:
Files to be converted. Value can be URL or file content. If used in >query or multipart content parameter must be suffixed with index >e.g. Files[0], Files1, Files[2]...
The following lines from the main function are the pertinent ones to the function in question:
//lodgingRecieptId is set to a url
const receiptFile = DriveApp.getFileById(lodgingReceiptId);
...
const copyID = frontPage.makeCopy().getId();
const copyDoc = DocumentApp.openById(copyID)
copyDoc.setName("MPD | " + sheet.getLastRow());
const body = copyDoc.getBody();
//find and replace in template copy
body.replaceText("{{AMOUNT}}",amount)
body.replaceText("{{CURRENT_DATE}}",current_date)
body.replaceText("{{LOCATION}}",location)
body.replaceText("{{PURPOSE}}",purpose);
body.replaceText("{{DEPART_DATE}}",formatLeaveDate);
body.replaceText("{{RETURN_DATE}}",formatReturnDate);
body.replaceText("{RSB} ",rsb);
body.replaceText("{{DAYS}}",days);
body.replaceText("{{MPD_AMOUNT}}",mpdAmount);
const docBlob = copyDoc.getAs('application/pdf');
docBlob.setName(copyDoc.getName() + ".pdf");
const copyPdf = DriveApp.createFile(docBlob);
//merge lodging receipt and template copy ——> Save id
mergePDFs(copyPdf,receiptFile)
From your showing script and your showing official document, how about the following modification?
Modified script:
Please replace <YOUR SECRET HERE> with your secret.
function mergePDFs(pdf1, pdf2) {
var fileValues = [pdf1.getBlob(), pdf2.getBlob()].map((e, i) => ({
"Name": e.getName() || `sample${i + 1}`,
"Data": Utilities.base64Encode(e.getBytes())
}));
var data = { "Parameters": [{ "Name": "Files", "FileValues": fileValues }, { "Name": "StoreFile", "Value": true }] };
var endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=<YOUR SECRET HERE>";
var options = {
'method': 'post',
'payload': JSON.stringify(data),
'contentType': "application/json",
'muteHttpExceptions': true
};
var res = UrlFetchApp.fetch(endpoint, options);
var outputPDFURL = JSON.parse(res.getContentText()).Files[0].Url;
var outputFile = UrlFetchApp.fetch(outputPDFURL).getBlob().setName("sampleOutput.pdf");
DriveApp.createFile(outputFile);
}
Note:
In this modification, it supposes that your secret is valid for using this API and pdf1 and pdf2 are the file object or the HTTPResponse object of the PDF data. Please be careful about this.
References:
Merge PDF API
fetch(url, params)
I'm trying to call a stored function in postgres 12 DB which takes 1 parameter of json type and returns result of json type.
The function is like this:
CREATE OR REPLACE FUNCTION public.get_users(
data json,
OUT result json)
RETURNS json
LANGUAGE 'plv8'
COST 100
VOLATILE
AS $BODY$const dataJson = JSON.parse(data);
const arg_id = dataJson.id;
const arg_token = dataJson.token;
const arg_ids = dataJson.ids.join(",");
result = {};
const getAuthUserResult = plv8.execute( 'SELECT id, token, deleted FROM public.users WHERE id = $1', [arg_id]);
const authUser = getAuthUserResult[0];
switch (true) {
case getAuthUserResult.length === 0: {
result.code = "ERR_SENDER_NOTFOUND";
break;
}
case authUser.token !== arg_token: {
result.code = "ERR_SENDER_INVALIDTOKEN";
break;
}
case authUser.deleted !== 0: {
result.code = "ERR_SENDER_DELETED";
break;
}
default: {
result.code = "OK"
}
}
if (result.code === "OK") {
result.users = plv8.execute( 'SELECT $1 FROM public.users WHERE id IN ($2)', ["name", arg_id]);
}
$BODY$;
ALTER FUNCTION public.get_users(json)
OWNER TO postgres;
The function must take a json with keys: "id" - for id of request sender, "token" - for it's secret and "targets" - for ids of target users, as follows:
{
"id": 448,
"token": "someToken",
"targets": [449, 450, 451]
}
But when I try calling the function by an SQL query:
SELECT * FROM get_users('{"id":448,"token":"someToken","targets":[449,450,451]}');
I get an error:
ERROR: SyntaxError: Unexpected token o in JSON at position 1
CONTEXT: undefined() LINE 0: [object Object]
SQL state: XX000
I have double checked json, and it seems to be valid. Also a lot of resources present this way of calling functions with json typed parameter. What can be wrong with the way I do it?
The problem was actually in the function code intself.
First:
const dataJson = JSON.parse(data);
const arg_id = dataJson.id;
This is invalid. The proper way to access json values is simple:
const arg_id = data.id;
And second:
return result;
is missing at the end.
This is my input
{
"AccountId": "9834e8cb-275a-4bff-b362-f216e9653686",
"ContactId": "9834e8cb-275a-4bff-b362-f216e9653686",
"AuthenticationDetails": {
"AuthenticationId": "{{clientId}}",
"AuthenticationType": "Token"
}
}
This is my output
{
"orderedByContactId": "36b8e4da-94fd-4680-a2d3-6b128e4b2584",
"orderedForContactId": "9834e8cb-275a-4bff-b362-f216e9653686"
}
I need to create a test (postman) to ensure that the output value ("orderedForContactId") matches the input value ("ContactId"). Can someone help me out?
Existing tests are in the following format:
pm.test("Response should contain orderedForContactId",function(){
let jsonRespData = pm.response.json();
pm.expect(jsonRespData).to.have.property('orderedForContactId');
});
Use this as your test script
pm.test("Response should contain orderedForContactId",function(){
var requestJson= JSON.parse(pm.request.body.raw);
var contactId = requestJson.ContactId.toString();
var responseJson = pm.response.json();
var orderedForContactId = responseJson.orderedForContactId;
pm.expect(orderedForContactId ).to.equal(contactId);
});
I changed the input to be
{
"AccountId": "9834e8cb-275a-4bff-b362-f216e9653686",
"ContactId": "{{ContactId}}",
"AuthenticationDetails": {
"AuthenticationId": "{{clientId}}",
"AuthenticationType": "Token"
}
}
And added the ContactId to the environment file.
Then I created the test below:
pm.test("Input ContactId should equal orderedForContactId",function(){
let jsonRespData = pm.response.json().orderedForContactId;
pm.expect(jsonRespData).to.equal(pm.environment.get("ContactId"))
});
I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}
Ajax is not populating my table with all the information from json encode values are {"name":"1","...":"Value"} fields with string values and the integers are not.
var idvalue = $("#modal-name"),
$.ajax({
type: "POST",
url: "ajax.php",
data: {
action: "getBudget",
userId : userId
},
success : function(data) {
//parse result as JSON
var res = JSON.parse(data);
//update modal fields
idvalue . text(res.name);
// other ID to populate
}
});
try to remove the space and replace the "," by a ";" in the first line: var idvalue = $("#modal-name");. It will resolve some of your problems.