Calling a JSON table with id variables that are numbers? - json

I am decently new to Lua, an I have been trying to work on API calling JSON tables. However, one particular JSON Table I am trying to process has identifiers that start with numbers. For example, one such table looks like this:
"data": {
"1001": {
"plaintext": "item title",
"description": "item description",
"id": 1001
}
}
When I try to decode the json file and print "data.1001.id" to the console, for example, I keep getting an error "malformed number near '.1001.id'".
I've looked at other similar questions on this site that say to put it in square brackets, such as "data.[1001].id" or "data.[[1001]].id", but when I do that I get the error " 'name' expected near '[[1001]]'".
Any help would be appreciated

You can use normal access as an array element []:
local json = require("json")
local j=[[
{
"data": {
"1001": {
"plaintext": "item title",
"description": "item description",
"id": 1001
}
}
}
]]
local d = json.decode(j)
print(d.data["1001"].description)

Related

PUT method doesn't work on Wordpress REST API

let me explain my problem
In my wordpress site I installed the WP REST API plugin to be able to read some listing fields via API
With postman if I use
GET https://mysitecom/wp-json/wp/v2/job-listings/1010
I get the following json correctly:
{
"id": 10565,
...
"status": "publish",
"type": "job_listing",
"title": "first try",
...
"_company_whatsapp": "",
"_company_mobile": "3331234567",
"_company_website": "",
"_company_use_social_networks": "",
"_company_facebook": "",
"_company_instagram": "",
...
}
If I want to edit 2 fields and use
PUT https://mysitecom/wp-json/wp/v2/job-listings/1010
with the following json:
{
"title": "edit try",
"_company_mobile": "3339999999",
}
It change the title but not the phone number.
If I try to change only the number with
{
"_company_mobile": "3339999999",
}
Postman returns this to me
{
"code": "rest_invalid_json",
"message": "JSON with invalid body was passed.",
"data": {
"status": 400,
"json_error_code": 4,
"json_error_message": "Syntax error"
}
}
I'm approaching the use of APi for the first time, what am I doing wrong? What is the problem and how can I fix it?
Thanks in advance
This json is invalid:
{
"_company_mobile": "3339999999",
}
You should remove the comma:
{
"_company_mobile": "3339999999"
}
Normally this is expected behaviour for PUT. You can skip fields only if they are optional. You cant pass only the field you want to update. Think of PUT like overwrite. The api applies the same validation like it will do for create (POST). Some APIs provide partial update with PATCH verb. Then you can provide only the fields you want to update usually as query params. Not sure what is exactly the case with Wordpress api.

Cypress Access Array element API response nested json

I cannot quite figure out how to access the 0th element in the array as part of the JSON body in order to check the API response. I have tried various ways and none seem to be correct.
I currently have the following as an example:
I'm guessing it is not difficult but for the life of me I can't figure it out. Thanks!
cy.get('#dogs')
.its('body')
.its('breeds[0]')
.its('names')
.should('include', {
count: ('10'),
});
Refer its. The indexes should be accessed individually with its.
Response JSON:
{
"sample": [
{ "names": ["Dummy 1", " Dummy 2"] },
{ "names": ["Dummy 3", " Dummy 4"] },
{ "names": ["Dummy 5", " Dummy 6"] }
]
}
The last object in the array should be accessed as:
// to check a child's length
cy.get('#sample')
.its('body') // 'responseBody' in case of latest cypress version
.its('sample')
.its('2')
.its('names')
.its('length')
.should('eq', 2);
// To check content
cy.get('#sample')
.its('body') // 'responseBody' in case of latest cypress version
.its('sample')
.its('2')
.its('names')
.its(1)
.should('include', '6');
Screenshot:

Data Factory - Retrieve value from field with dash "-" from JSON file

In my pipeline I reach through REST API using GET request to a 3rd party database. As an output I receive a bunch of JSON files. The number of JSON files I have to download (same as number of iterations I will have to use) is in one of the fields in JSON file. The problem is that the field's name is 'page-count' which contains "-".
#activity('Lookup1').output.firstRow.meta.page.page-count
Data Factory considers dash in field's name as a minus sign, so I get an error instead of value from that field.
{"code":"BadRequest","message":"ErrorCode=InvalidTemplate, ErrorMessage=Unable to parse expression 'activity('Lookup1').output.firstRow.meta.page.['page-count']'","target":"pipeline/Product_pull/runid/f615-4aa0-8fcb-5c0a144","details":null,"error":null}
This is how the structure of JSON file looks like:
"firstRow": {
"meta": {
"page": {
"number": 1,
"size": 1,
"page-count": 7300,
"record-count": 7300
},
"non-compliant-record-count": 7267
}
},
"effectiveIntegrationRuntime": "intergrationRuntimeTest1",
"billingReference": {
"activityType": "PipelineActivity",
"billableDuration": [
{
"meterType": "SelfhostedIR",
"duration": 0.016666666666666666,
"unit": "Hours"
}
]
},
"durationInQueue": {
"integrationRuntimeQueue": 1
}
}
How to solve this problem?
The below syntax works when retrieving the value for a json element with a hyphen. It is otherwise treated as a minus sign by the parser. It does not seem to be documented by Microsoft however I managed to get this to work through trial and error on a project of mine.
#activity('Lookup1').output.firstRow.meta.page['page-count']
This worked for us too. We had the same issue where we couldn't reference an output field that contained a dash(-). We referenced this post and used the square brackets and single quote and it worked!
Example below.
#activity('get_token').output.ADFWebActivityResponseHeaders['Set-Cookie']

$filter on schema extensions microsoft graph doesn't support 'contains'

I added a schema extension to users in my org, to keep track of training a user has taken. Since lists are not supported I am trying to store this as a comma separated string, as follows:
{
"id": "voctestextension",
"description": "voc test extension",
"targetTypes": ["User"],
"properties": [
{
"name": "trainings",
"type": "String"
}
]
}
Now, while trying to fetch the users who have taken training 'X' I am making the below call:
https://graph.microsoft.com/v1.0/users?$filter=contains(extrw7rtbc9_voctestextension/trainings, 'Azure'), $select=extrw7rtbc9_voctestextension,displayName
This doesn't give the correct response, but throws this error:
{
"error": {
"code": "Request_UnsupportedQuery",
"message": "Unsupported Query.",
"innerError": {
"request-id": "dc3fda19-6464-43d9-95ce-54a0567bf5a9",
"date": "2018-03-15T09:14:30"
}
}
}
From different forum answers, I understand that contains is not supported. Can you suggest a better way to track this info in the user's profile?
Contains is not supported. You need to use startswith or add multiple properties like training1, training2, training3.. and then use filter with ORs and EQs.
https://graph.microsoft.com/v1.0/users?$filter(extrw7rtbc9_voctestextension/trainign1 eq 'Azure' or extrw7rtbc9_voctestextension/trainign2 eq 'Azure')
Kepaas solution is working (almost) perfectly, but the "=" is missing after "$filter":
https://graph.microsoft.com/v1.0/users?$filter=(extrw7rtbc9_voctestextension/trainign1 eq 'Azure' or extrw7rtbc9_voctestextension/trainign2 eq 'Azure')

Convert string to JSON in Freemarker

Any ways on how we can convert VALID JSON STRING to actual JSON(sequence) in freemarker. I mean this string is actually returned by a JSON.stringify() call.
I follow what this post says but it seems this is not applicable to mine.
<#assign test = "(record.custpage_lineitems?json_string)">
<#assign m = test?eval>
<#list m as k>
${k.item}
</#list>
ERROR says
Expected collection or sequence. m evaluated instead to freemarker.template.SimpleScalar on line 286, column 32 in template.
Sample JSON String
{
"34952": {
"item": "TRAVEL",
"notes": "Travel Time To Client Site to Perform Repairs.1.0",
"type": "Service"
},
"34963": {
"item": "MECHANIC RECOMMENDATION",
"notes": "MECHANIC RECOMMENDATION\nr&r drive tires 21x7x15 smooth black \nr&r lp tank latch on bracket \nr&r lp hose cupler",
"type": "Service"
},
"9938": {
"item": "T1",
"notes": "Field Service Call Charge75$ labor 124$",
"type": "Service"
},
"34549": {
"item": "GENERAL SERVICE INFO",
"notes": "SERVICE NOTES:\ndrove to customer location found lift found to broken hydraulic hoses had to remove attachment in order to remove broken hoses then drove to get hoses made installed hoses back on lift re installed loose brackets I found out attachment back on lift topped off hydraulic resivoir and lift was ready",
"type": "Service"
},
"36264": {
"item": "FSO PARTS (UN CHECK IF NEEDED)",
"notes": "MARK CHECK IF PARTS NOT NEEDED.",
"type": "Service"
},
"36266": {
"item": "FSO QUOTE (UN CHECK IF NEEDED)",
"notes": "MARK CHECK IF QUOTE NOT NEEDED.",
"type": "Service"
},
"29680": {
"item": "0199992-HY32F",
"notes": "2 x 0199992-HY32F",
"type": "Inventory Item"
}
}
It seems that it is not converting to a valid sequence because if i'll try to print ${m} it displays the escaped json string.
I am looking for a way that I will just say <#assign test=toJSON(record.custpage_lineitems) but I think you have to write methods in java since I am doing this in 'netsuite'
UPDATE: I tried to hard code the json string like
<#assign m = '{"34952":{"item":"TRAVEL","notes":"Travel Time To Client Site to Perform Repairs.1.0","type":"Service"}....}'>
and try to loop through, it seems working. But if I substitute the value of m to myvariable seems not working. I am 100% sure myvariable is not null nor empty but contains the same JSON string.
My assessment is that, if I could just wrap the myvariable to single quote then I think it will solve the issue. I tried
<#assign m = 'myvariable'> and
<#assign m = '(myvariable)'> and
<#assign m = '(${myvariable})'> and
<#assign m = '(myvariable?string)'> etc.
but none is correct. Can someone just direct me into what is the proper syntax on how to wrap existing variable to single quote.
Any help guys? Thanks.
I think the \n inside the json string could cause some problems. Try replacing it first with (or something similar what will suit your needs)
record.custpage_lineitems?replace("\n", "\\n")
and then do the eval
If your record.custpage_lineitems is already a stringified JSON then you do not have to use ?json_string.
Replace your first two lines with this:
<#assign m = record.custpage_lineitems?eval>
See eval documentation for details.
Update:
Your custpage_lineitems is a hash map and #list accepts sequence. Try this:
<#list m?keys as k>
${m[k].item}
</#list>