Convert string to JSON in Freemarker - json

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>

Related

PostgreSQL: error with parse JSON with ''

can you get advise me how I can fix the error when I try to parse JSON from PostgreSQL table?
ERROR: invalid input syntax for type json Hint: Token "'" is invalid. Where: JSON data, line 1: [{'...
I have researched this issue and see that it comes up due to the fact that some contain '' in JSON:
[{'name':'cc','desc':'What is your credit card number? I promise to keep it real secure like.','type':'string','regex':'\\d+','min_length':1,'max_length':16,'example':'736363627'},{'name':'height','desc':'How tall are you?','type':'int','min':4,'max':666,'example':55},{'name':'likescake','desc':'Do you like cake?','type':'bool'},{'name':'address','desc':'What is your address','type':'string','min_length':5,'example':'blk 6 lot 26 blah blah'},{'name':'single','desc':'Are you single?','type':'bool'},{'name':'weight','desc':'what is your weight in kgs?','type':'float','example':55}]
another JSONs contain "":
[{"desc": "What is your credit card number? I promise to keep it real secure like.", "name": "cc", "type": "string", "regex": "\\d+", "max_length": 16, "min_length": 1}, {"max": "666", "min": "4", "desc": "How tall are you?", "name": "height", "type": "int"}, {"desc": "Do you like cake?", "name": "likescake", "type": "bool"}]
I try to parse with this command:
-- For multiple choice from JSON
SELECT
s.projectid,
s.prompttype,
el.inputs->>'name' AS name,
el.inputs->>'desc' AS desc,
el.inputs->>'values' AS values,
s.created,
s.modified
FROM source_redshift.staticprompts AS s,
jsonb_array_elements(s.inputs::jsonb) el(inputs);
As #Jim-Jones said, JSON is invalid.
There are many online and offline JSON validation tools. I recomend to use it.
Its help you detect the cause of problems: is it invalid JSON or error in your code.
For example, JSON Formatter said that it replaced incorrect quotes.

JSON path evaluation

given this node in a json response:
{
"name": "RFM912Feilkode",
"valueCodeableConcept": {
"coding": [
{
"system": "http://xxx/error-code",
"code": "0"
}
],
"text": "OK"
}
I want to verify that the text "OK" is present in Gatling using Scala syntax.
Something (pseudo code ish):
.check(jsonPath("$..valueCodeableConcept.text").is("OK"))
but this does not work. Any tips on how to "hit" the OK value and check if it exists?
Your json isn't valid. Missing curly bracket.
I tried this and all works fine:
.check(jsonPath("$.valueCodeableConcept.text").is("OK"))
If you want to extract some json based on other elements in the json (what you seem to be getting at in the comments on other answers), then you can use filters in the jsonPath like
$.[?(#.name=="RFM912Feilkode")].valueCodeableConcept.text
which will get you the text element from valueCodeableConcept where the associated name is RFM912Feilkode

Does config.GetSection not work in Azure Functions? And what is the recommended alternative?

Azure Function with a complex (List of objects) configuration type is working locally (with that complex type in local.settings.json) but fails to read / create list of objects in Azure (with that complex type in Azure Function configuration settings). I'm looking for the recommended / optimal way to support that across both platforms / methods of access.
This works great in my local.settings.json where I use the configuration builder and pull data out like
var myList = config.GetSection("ConfigurationList").Get<List<MyType>>();
however this doesn't seem to work in Azure Functions?? Now I think that is because in local.settings.json it is a json file and looks like
"ConfigurationList" : [ { "Name": "A", "Value": 2 }, { "Name": "B", "Value": 3 }]
while in Azure Functions it is a setting "ConfigurationList" with the value
[ { "Name": "A", "Value": 2 }, { "Name": "B", "Value": 3 }]
(so there isn't really a "section" in Azure Functions?)
It seems like the "easy" solution to this is to just change the .json to be a quoted string and deserialize the string (and then it would work the same in both places); but that doesn't seem like it would be the "best" (or "recommended" solution)
i.e. something like
"ConfigurationList" : "[ { \"Name\": \"A\", \"Value\": 2 }, { \"Name\": \"B\", \"Value\": 3 }]"
var myList = (List<MyType>)JsonConvert.DeserializeObject(config["ConfigurationList"], typeof(List<MyType>));
Which isn't the worst; but makes the json a bit "not as nice" and doesn't "flow" across the two platforms ... if it is what I have to do, fine; but hoping for a more standard approach / recommendation
As I metioned in the comment, on local you can process local.settings.json as a json file, but when on azure, the value in configuration settings is environment variable. There is no section, it just string.
Please notice that only string values are allowed, and that anything nested will break. Learn how to use nest settings on azure web app(azure functon is based on azure app service sandbox, so it is the same.):
https://learn.microsoft.com/en-us/archive/blogs/waws/asp-net-core-settings-for-azure-app-service
For example, if this is the json structure:
{
"Parent": {
"ChildOne": "C1 from secrets.json",
"ChildTwo": "C2 from secrets.json"
}
}
Then in web app, you should save it like this:
(source: windows.net)
Not sure if you are looking something like this , it seems a list but if it is a simple JObject like
"ConfigurationList" : {
"Name": "A",
"Value": 2
}
Then you can declare ConfigurationList:Name , ConfigurationList:Value in the configuration settings of function app

Zapier Catch (Raw) Hook JSON parsing issue

I would like to configure sync between two different CRMs (Clevertap and Intercom) using Zapier and Webhooks. In general Clevertap sends the following JSON to webhook:
{
"targetId": 1548328164,
"profiles": [
{
"event_properties": {
"MSG-sms": true,
"MSG-push": true,
"businessRole": "EMPLOYEE",
"Mobile Number": "123123123123",
"Name": "Artem Hovtvianisa",
"Title": "Mr",
"Last Name": "Hovtvianisa",
"Gender": "M",
"Customer type": "Business Account Holder",
"MSG-email": true,
"First Name": "Artem",
"Last seen IP": "111.177.74.50",
"tz": "GMT+0200",
"International customer": "yes",
"isBusiness": true,
"Email": "xxxyyy#gmail.com",
"Identity": 15675
},
"objectId": "e32e4de3c1e84b2d9bab3707c92cd092",
"all_identities": [
"15675",
"xxxyyy#gmail.com"
],
"email": "xxxyyy#gmail.com",
"identity": "15675"
}
]
}
Zapier provides two types of catch webhook: regular and Raw.
Catch Raw Hook
When I use this type, JSON raw data will be handled OK and on the next step (Zapier JS code app) I am able to pass proper JSON data like in example above.
However when I use simple JS code to parse JSON object and get profiles[0] array value I get the following error "TypeError: Cannot read property '0' of undefined"
JS Code from Code step:
var result = JSON.parse(JSON.stringify(inputData));
console.log(result.profiles[0]);
return result;
Catch Hook
In case I use regular Catch Hook, hook parse data in some odd way, like this:
JSON.parse cannot recognize this structure.
Please advise how can I handle Webhook Zapier step in a proper way in order to get profiles[0] array item values?
Thanks in advance!
David here, from the Zapier Platform team. You're on the right track!
Catch Raw Hook is the way to go here. Your issue is that the data is coming in as a string and you're re-stringifying it before parsing it, which gets you back to where you came from. A simpler version:
JSON.stringify("asdf") // => "\"asdf\"", quotes in the string
JSON.parse("\"asdf\"") // => "asdf", the original string
"asdf".profiles // => undefined
undefined[0] // => error, cannot read property "0" of undefined
Instead, just parse it and you're good to go!
// all your variables are already in "inputData", so yours,
// also named inputData, must be referenced explicitly.
const result = JSON.parse(inputData.inputData);
return {result: result, firstProfile: result.profiles[0]};

$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')