Value of json has multiple data-types (json-shema) - jsonschema

I have a question about json-schema on karatedsl..
For example i have a json, and one of the key of the json have multiple data-type (for example, it could be #string or #object)
How to validate json that have multiple data-type on karatedsl ??
Example #string :
{
"customer_id":"081234562002",
"order_id":"",
"amount":20700,
"price":20700,
"created":1560684244,
"changed":1560684246,
"data":"Internal Server Error"
}
Example #object :
{
"customer_id":"081234562002",
"order_id":"",
"amount":20700,
"price":20700,
"created":1560684244,
"changed":1560684246,
"data":
{"message": "Internal Server Error"}
}
And i have separated json file for validate the json above, like this :
{
"customer_id":"#string",
"order_id":"#string",
"amount":"#number",
"price":"#number",
"created":"#number",
"changed":"#number",
"data":"???"
}

There are multiple options in karate to do this, i can give one quick example here,
* match response.myKey == "#? karate.match(_,'#string').pass || karate.match(_,'#object').pass"
since we need markers like #string i have to use karate.match. you can write any function that return boolean and use it here as a substitute.
read fuzzy matching, Self validation expression , Schema Validation from karate docs
Edit: for updated question
replace your ??? as
"#? karate.match(_,'Internal Server Error').pass || karate.match(_,{'message' :'Internal Server Error'} ).pass"

Related

Logic App: SQL Query Returns XML as JSON challenge

My SQL query returns XML data in SQL Server (with For XML). When I execute the query (Execute a SQL Query) in Logic Apps it returns the XML as JSON. I need to pass the XML to a Dynamics 365 integration in Logic Apps with a HTTP Post.
The query is (I removed the subqueries)
select
[JOURNALBATCHNUMBER],
[JOURNALNAME],
[DESCRIPTION],
[PAYMENTFILEID],
[BATCHTOTALFROMSOURCEREAL],
from ait.ImportMSSPaymentJournal for xml raw ('CUSTOMERPAYMENTJOURNALHEADERENTITY'), type, elements
The action output (without all the XML):
"body": {
"ResultSets": {
"Table1": [
{
"": "<CUSTOMERPAYMENTJOURNALHEADERENTITY><JOURNALBATCHNUMBER>A-1234</JOURNALBATCHNUMBER><JOURNALNAME>MSS</JOURNALNAME><DESCRIPTION>Customer Payment-Mass Payer</DESCRIPTION><PAYMENTFILEID>MSS - May 17 2021 6:00PM</PAYMENTFILEID><BATCHTOTALFROMSOURCEREAL>10685.830000</BATCHTOTALFROMSOURCEREAL><CUSTOMERPAYMENTJOURNALLINEENTITY><JOURNALBATCHNUMBER>A-1234</JOURNALBATCHNUMBER><LINENUMBER>494</LINENUMBER><ACCOUNTDISPLAYVALUE>000200000701</ACCOUNTDISPLAYVALUE><ACCOUNTTYPE>Cust</ACCOUNTTYPE><BANKTRANSACTIONTYPE>Check</BANKTRANSACTIONTYPE><COMPANY>XX</COMPANY><CREDITAMOUNT>6800.000000</CREDITAMOUNT><CURRENCYCODE>USD</CURRENCYCODE><CUSTOMERNAME /><DEBITAMOUNT>0.000000</DEBITAMOUNT><OFFSETACCOUNTDISPLAYVALUE>US2969</OFFSETACCOUNTDISPLAYVALUE><OFFSETACCOUNTTYPE>Bank</OFFSETACCOUNTTYPE><OFFSETCOMPANY>XX</OFFSETCOMPANY><PAYMENTMETHODNAME>Check</PAYMENTMETHODNAME><POSTINGPROFILE>GEN</POSTINGPROFILE><AUTOSETTLED>No</AUTOSETTLED><BILLYEAR>2020</BILLYEAR><NSFGROUPID /><PT
}
]
},
"OutputParameters": {}
}
}
What I don't know is how do I reference the XML in the HTTP Post? Do I need to transform the JSON to XML? Or Use a different LA action to execute the query?
Thanks very much!
Tom
The correct notation to reference the result set from the query action eluded me for awhile. What finally worked, using the example above, is
body('MyQuery')?['resultsets']?['Table1']?[0]?['']

How do i navigate the path of a json object that has namespace prefixes (eg n1:, n7: ) in sql server using OPENJSON?

I want to obtain xml files from an API (I can not get Json formats from this API). Thereafter i want to convert them to JSON and then save then to oneDrive using a logic app. (I intend to create tables from these json files in Azure SQL server)
My approach so far is trigger the logic app with an HTTP GET response.
convert the recieved xml file from step 1 above to json using json(xml(triggerBody())) and save it to oneDrive.
The logic App steps are: 1) GET an HTTP response from the API 2) Save the response as json on oneDrive using the function json(xml(triggerBody()))
here is a copy of the xml file from the API:
<?xml version="1.0" encoding="ISO-8859-1"?>
-<n1:VareResult xmlns:n1="http://ABCC.Schemas.Vare/8.0" xmlns:n7="http://ABCC.Schemas.Common/8.0">
-<n1:Header>
-<n1:EksportType>
<n7:EksportId>0</n7:EksportId>
<n7:Eksportmetode/>
<n7:StartIndex>0</n7:StartIndex>
<n7:BatchSize>2000</n7:BatchSize>
<n7:TotalCount>1</n7:TotalCount>
<n7:VersionNr/>
</n1:EksportType>
-<n1:Result> <n7:ResultValue>Success</n7:ResultValue> </n1:Result>
</n1:Header>
-<n1:VareListe>
-<n1:Vare>
-<n1:Status>
<n7:Created>2004-06-27T15:30:57.549</n7:Created>
<n7:Updated>2019-11-20T09:34:03.008</n7:Updated>
</n1:Status>
<n1:ABCCNr>10203</n1:ABCCNr>
........
........
Here is its corresponding json file:
{"?xml":{"#version":"1.0","#encoding":"iso-8859-1"},"n1:VareResult":
{"#xmlns:n7":"http://ABCC.Schemas.Common/8.0","#xmlns:n1":"http://ABCC.Schemas.Vare/8.0","n1:Header":
{"n1:EksportType":
{"n7:EksportId":"0","n7:Eksportmetode":null,"n7:StartIndex":"0","n7:BatchSize":"2000","n7:TotalCount":
"1","n7:VersionNr":null},"n1:Result":{"n7:ResultValue":"Success"}},"n1:VareListe":{"n1:Vare":
{"n1:Status":{"n7:Created":"2004-06-27T15:30:57.549","n7:Updated":"2019-11-20T09:34:03.008"},
"n1:ABCCNr":"10203",
........
.......
As you see the json file has namespace prefixes too. I am trying to navigate the path in sql server. Here is the example:
Image below shows result from the command: select * FROM OPENJSON(#jsonObject)
I want to access the values for the key n1:VareResult.
I have tried to navigate the path like this: select * FROM OPENJSON (#jsonObject,'$.n1:VareResult' )
But I get the error: "JSON path is not properly formatted. Unexpected character ':' is found at position 4."
Is there an escape sequence that can let me navigate the path even if it has these 'forbidden characters'?
If not is there a way i can control the conversion from xml to json in step 2 above so that the namespace prefixes are omitted for each element?
Let me give you an example for this, then you can try somethins like this:
DECLARE #json NVARCHAR(4000) = N'{
"path": {
"to":{
"sub-object":["en-GB", "en-UK","de-AT","es-AR","sr-Cyrl"]
}
}
}';
SELECT [key], value
FROM OPENJSON(#json,'$.path.to."sub-object"')
Additional reference:
https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver15
Hope it helps.
Using the tip from: https://stackoverflow.com/a/45873164/10404094, I added double quotes around the field names in sql server and it worked. Just like this:
select * FROM OPENJSON (#jsonObject, '$."n1:VareResult"."n1:VareListe"."n1:Vare" ')
This fixed my problem! Thanks stackoverflow!

Karate not supporting JSON Path [duplicate]

This question already has an answer here:
Karate: one liner json path expression not working
(1 answer)
Closed 1 year ago.
I have a JSON path, say $[advertiserId] and this evaluates to
[
"001E000000yBFskIAG"
]
using tool https://jsonpath.com/? .
However, the equivalent Karate syntax does not work:
And match response[*].advertiserId == '001E000000yBFskIAG'
It does not recogize this path.
If I have JSON:
{
"advertiserId":"someID"
}
Then
And match response[*].advertiserId == 'someID'
should work. Karate ought to be able to support basic JSON matching.
Karate is stricter - if there is JsonPath "wildcard" e.g. * or .. the result will always be an array. Maybe jsonpath.com converts a single element array to the value for convenience - but we will never do that.
The below works:
* def response = [{ advertiserId: '001E000000yBFskIAG' }]
* match response[*].advertiserId == ['001E000000yBFskIAG']

Jmeter Parsing specific id in another request

I need to fetch id parameter from JSON and parse that id value in another request URL. Issue is in JSON i am getting multiple values of id like 6, Etc/UTC etc. I want only integer value to pass.
Please suggest solution for automate this instead of passing value everytime.
You can add regex expression to you JSON expression
$..book[?(#.author =~ /.*REES/i)] All books matching regex (ignore case)
In your case add regular expression for numbers:
=~ /.*(\d+)/i)]
My expectation is that you need to amend your JSON Path query to fetch not all IDs but only the ID(s) which is(are) numeric. Unfortunately without seeing your response and JSON Path query we cannot suggest anything meaningful.
Looking into your response I can only suggest only getting the first numeric ID using JSR223 PostProcessor and Groovy language.
Add JSR223 PostProcessor after the JSON Extractor
Put the following code into "Script" area:
for (int i = 1; i <= (vars.get('id_matchNr') as int); i++) {
def currentVar = vars.get('id_' + i)
if (currentVar =~ '(\\d+)') {
vars.put('someid', currentVar)
break;
}
}
You will be able to access the first numeric ID as ${someid} where required.

Can we validate dynamically generated values like datetime or any other number in Karate DSL

Can we validate dynamically generated values like datetime or any other number in Karate DSL. If yes, could you please tell how do we do it ?
Just make a JavaScript function replicating that dynamic value. and then do karate matching.
* def datetime = function(){code_generating_Date_time}
Then match datetime == response.datetime
Although i feel like generating the function should not be done, because it may become non-deterministic
Would suggest redesigning the test case.
Yes.
For example if the response is { id: 'a9f7a56b-8d5c-455c-9d13-808461d17b91', name: 'Billie' }
You can assert this way:
{ id: '#string', name: 'Billie' }
Please read the documentation, because all of this is explained there: https://github.com/intuit/karate#fuzzy-matching