How to use variable in JMESPath expression? - json

The regular expression works perfect as below:
jmespath.search(currentStats, 'Items[?Name == Annie]')
But I want to make my filtered key as a variable.
I have tried
var name = "Annie"
jmespath.search(JSONdata, 'Items[?Name == %s]' %name;)
Which does not work.
Many thanks in advance.

There's no built-in way in jmespath or the search function to template values into the query string, but you can safely embed JSON literals with backticks, however your language allows it.
var name = "Annie";
var result = jmespath.search(JSONdata, 'Items[?Name == `' + JSON.stringify(name).replace('`','\\`') + '`]');
We need to convert the string to JSON, escape any backticks in that string and then wrap it in backticks. Let's wrap that into a function to make it a bit nicer to read:
function jmespath_escape(item) {
return '`' + JSON.stringify(item).replace('`','\\`') + '`';
}
var name = "Annie";
var result = jmespath.search(JSONdata, 'Items[?Name == ' + jmespath_escape(name) + ']');

Related

remove [" from string is SSIS using derived column

I am trying to remove [" from beginning of the string and "] end of the string by using REPLACE function in derived column. But it is giving an error.
I have used the below formula
REPLACE(columnanme,"["","")
is used in the to remove [" in the beginning of the string. But not working.
Can someone help me on this.
Note: Data is in table and datatype is NTEXT
Regards,
Khatija
I believe you just need to escape the " value
so
\”
REPLACE(columnanme,"[\"","")
otherwise it sees the " in the middle as the closing quote and you have an invalid statement.
I am trying to remove [" from beginning of the string and "] end of the string
Supposing that we reliably have brackets and quotes wrapping the data, the simplest approach would be to use substring. This would be easier to do in SQL:
UPDATE myTable SET columnname = SUBSTRING(columnname, 3, LEN(columnname) -4)
WHERE columnname LIKE '["%"]'
If you want to do this in SSIS, you'll need to use a script component transformation to avoid data loss when converting the value to a string. Select the column you want to work with and set the usage type to ReadWrite:
In the script, I have added a method GetNewString, which converts the blob to a string and strips the unwanted characters. You can also use Replace or Regex.Replace if that makes more sense.
In the Input0_ProcessInputRow method, we convert the columns data, reset the blob and then add the new value:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
var input = GetNewString(Row.columname);
Row.columname.ResetBlobData();
Row.columname.AddBlobData(System.Text.Encoding.Unicode.GetBytes(input));
}
public string GetNewString(Microsoft.SqlServer.Dts.Pipeline.BlobColumn blobColumn)
{
if (blobColumn.IsNull)
return string.Empty;
var blobData = blobColumn.GetBlobData(0, (int)blobColumn.Length);
var stringData = System.Text.Encoding.Unicode.GetString(blobData);
stringData = stringData.Substring(2, stringData.Length - 4);
return stringData;
}

Remove some special character "[ ]" from a string

I'm new to flex coding, for example if I have a string like "[123-456],[456-789]"
and I want to remove all the "[" and "]" which result in:
"123-456,456-789"
can string.replace() or trim() do the job for me?
tried several times still fail
In this case string.replace() should do the job!
Please see the documentation for String.replace()
var st: String = "[123-456],[456-789]";
var p1: RegExp = /\[|\]/g;
st = st.replace(p1, "");
trace(st) //"123-456,456-789"

How to filter based on multiple condition: ReactJS

Im playing around with React and json data, i have an input field to search data from the json file.
I can figure out how to search one key of the json data, is there any chance of some help.
My code is:
if(searchString.length > 0){
contactsData = contactsData.filter(function(l){
return l.name.toLowerCase().match( searchString );
});
}
where l.name i also want l.company and l.email.
One simple solution is concatenate all the three strings by using some character like *, # or any other, then check for searchString.
Like this:
if(searchString.length > 0){
let str;
contactsData = contactsData.filter(function(l){
str = `${l.name}# ${l.company}# ${l.email}`;
return str.toLowerCase().match( searchString );
});
}
Or you can individually check also, like this:
return (
l.name.toLowerCase().match( searchString ) ||
l.company.toLowerCase().match( searchString ) ||
l.email.toLowerCase().match( searchString )
);
search on multiple condition
in the given array you can search against firstName,lastName,email,phone.
if search query matched any of this values it will result of that.
{[{firstName:'Ali',lastName:'khan',email:'test#email.com',phone:12345}] .filter((a) =>
${a.firstName} ${a.lastName} ${a.email} ${a.phone}.includes(
your search filed value here
)
)

Parsing a String That's Kind of JSON

I have a set of strings that's JSONish, but totally JSON uncompliant. It's also kind of CSV, but values themselves sometimes have commas.
The strings look like this:
ATTRIBUTE: Value of this attribute, ATTRIBUTE2: Another value, but this one has a comma in it, ATTRIBUTE3:, another value...
The only two patterns I can see that would mostly work are that the attribute names are in caps and followed by a : and space. After the first attribute, the pattern is , name-in-caps : space.
The data is stored in Redshift, so I was going to see if I can use regex to resolved this, but my regex knowledge is limited - where would I start?
If not, I'll resort to python hacking.
What you're describing would be something like:
^([A-Z\d]+?): (.*?), ([A-Z\d]+?): (.*?), ([A-Z\d]+?): (.*)$
Though this answer would imply your third attribute value doesn't really start with a comma, and that your attributes name could countain numbers.
If we take this appart:
[A-Z\d] Capital letters and numbers
+?: As many as needed, up to the first :
(.*?), a space, then as many characters as needed up to a coma and a space
^ and $ The begining and the end of a string, respectively
And the rest is a repetition of that pattern.
The ( ) are just meant to identify your capture sections, in this case, they don't impact directly the match.
Here's a working example
Often regex is not the right tool to use when it seems like it is.
Read this thoughtful post for details: https://softwareengineering.stackexchange.com/questions/223634/what-is-meant-by-now-you-have-two-problems
When a simpler scheme will do, use it! Here is one scheme that would successfully parse the structure as long as colons only occur between attributes and values, and not in them:
Code
static void Main(string[] args)
{
string data = "ATTRIBUTE: Value of this attribute,ATTRIBUTE2: Another value, but this one has a comma in it,ATTRIBUTE3:, another value,value1,ATTRIBUTE4:end of file";
Console.WriteLine();
Console.WriteLine("As an String");
Console.WriteLine();
Console.WriteLine(data);
string[] arr = data.Split(new[] { ":" }, StringSplitOptions.None);
Dictionary<string, string> attributeNameToValue = new Dictionary<string, string>();
Console.WriteLine();
Console.WriteLine("As an Array Split on ':'");
Console.WriteLine();
Console.WriteLine("{\"" + String.Join("\",\"", arr) + "\"}");
string currentAttribute = null;
string currentValue = null;
for (int i = 0; i < arr.Length; i++)
{
if (i == 0)
{
// The first element only has the first attribute name
currentAttribute = arr[i].Trim();
}
else if (i == arr.Length - 1)
{
// The last element only has the final value
attributeNameToValue[currentAttribute] = arr[i].Trim();
}
else
{
int indexOfLastComma = arr[i].LastIndexOf(",");
currentValue = arr[i].Substring(0, indexOfLastComma).Trim();
string nextAttribute = arr[i].Substring(indexOfLastComma + 1).Trim();
attributeNameToValue[currentAttribute] = currentValue;
currentAttribute = nextAttribute;
}
}
Console.WriteLine();
Console.WriteLine("As a Dictionary");
Console.WriteLine();
foreach (string key in attributeNameToValue.Keys)
{
Console.WriteLine(key + " : " + attributeNameToValue[key]);
}
}
Output:
As an String
ATTRIBUTE: Value of this attribute,ATTRIBUTE2: Another value, but this one has a comma in it,ATTRIBUTE3:, another value,value1,ATTRIBUTE4:end of file
As an Array Split on ':'
{"ATTRIBUTE"," Value of this attribute,ATTRIBUTE2"," Another value, but this one has a comma in it,ATTRIBUTE3",", another value,value1,ATTRIBUTE4","end of file"}
As a Dictionary
ATTRIBUTE : Value of this attribute
ATTRIBUTE2 : Another value, but this one has a comma in it
ATTRIBUTE3 : , another value,value1
ATTRIBUTE4 : end of file

AS3 Custom string formula parser

My goal is to create some kind of Parser to parse string formulas, similar to Excel formulas.
Formula string example (barcode example) -
"CONCAT('98', ZEROFILL([productNumber],5,'0'), ZEROFILL(EQUATION([weightKG]*1000),5,'0'))"
where
'98' - String
[productNumber] and [weightKG] - are variables that can be changed
CONCAT, ZEROFILL and EQUATION are methods which exist in class
For this formula with variables [productNumber] = '1' and [weightKG] = 0.1 result must be
'980000100100'
The question is how to split/parse whole string to parts and detect methods, variables and string values?
Another idea occurred, while i was typing - is to store whole formula in XML format.
Thank You.
You can use String.split() to get an array of substrings.
However, using your example, calling split(",") would give you the following array:
[0]=CONCAT('98'
[1]= ZEROFILL([productNumber]
[2]=5
[3]='0')
[4]= ZEROFILL(EQUATION([weightKG]*1000)
[5]=5
[6]='0'))
That doesn't seem like it will be very helpful for your project. Instead, you might think about creating a parse() function with some logic to find useful substrings:
function parse(input:String):Array {
var firstParen:int = input.indexOf("(");
var lastParen:int = input.lastIndexOf(")");
var formulaName:String = input.substring(0, firstParen);
var arguments:String = input.substring(firstParen, lastParen);
var argumentList:Array = parseArgs(arguments);
var result:Array = new Array();
result.push(formulaName);
//Recursively call parse() on the argumentList
foreach (var elem:* in argumentList) {
result.push(elem); //Could be string or array.
}
}
function parseArgs(input:String):Array {
// Look for commas that aren't enclosed inside parenthesis and
// construct an array of substrings based on that.
//A regex may be helpful here, but the implementation is left
//as an exercise for the reader.
}