Which do you prefer, and why:
Typical
if (this.sun.hidden === true &&
this.moon.visible === false) {
print "its daytime"
}
Possible unnecessary abstraction
if (isSunHidden() === true &&
isMoonVisible() === false) {
print "its daytime"
}
Removing some syntax
if (isSunHidden() &&
isMoonVisible()) {
print "its daytime"
}
I like this one as its very readable, but also requires a hard-coded "daytime" string
if (timeOfDay() === "daytime") {
print "its daytime"
}
This is also easy to read
if (isItDaytime()) {
print "its daytime"
}
Mixes printing with time of day checking, not good
printDaytime();
Anyway, this is personal preference to a large degree, but there also good, logical reasons to prefer one over the other and I am interested in hearing those reasons - or possibly other variations of the same construct if it adds anything.
Thanks!
Of your options, I prefer:
if (isItDaytime()) {
print "its daytime"
}
This one is also not terrible:
if (timeOfDay() === "daytime") {
print "its daytime"
}
...though I would use an enumeration or similar construct instead of the literal string, like:
if (timeOfDay() === TimeOfDay.DAY_TIME) {
print "its daytime"
}
Related
Hi i'm new to Logstash and Grok syntax, I'm trying to understand what are those line meaning
codec => multiline { pattern => "^{$" negate => "true" what => "previous" }
and
mutate {
gsub => ["message", "'", '"']
}
Thanks !
it is pretty well explain in the official documentation of the multiline codec plugin:
pattern => ^{$ matches lines that only contain a { character and end immediately
negate => true means that line NOT matching the pattern are considered
what => previous means that the current matched line relates to the previous one
In summary, these settings mean that all lines that do NOT consist of only { belong to the previous line.
Concretely, this multiline filter is for putting together JSON data that was pretty-printed on several line, like this:
{
"bla": {
"test": 1
}
}
The above pretty-printed JSON will be handled as if it had been printed as a single line, like this:
{ "bla": { "test": 1 } }
Regarding the second filter (mutate/gsub), it is used to replace all single quotes with double quotes.
Pulling my hair here, trying to use jq to parse and extend a JSON file and adding an element at a specific position based on a certain condition.
Here is a sample file (also at https://jqplay.org/s/6cjmbnvrqu)
{
"TopA": { "stuff": "here"},
"TopB": {
"C591AB7E": {
"Type": "this",
"Properties": {
"lots": 1,
"of": 2,
"values" : 3
}
},
"7E16765A": {
"Type": "this",
"Properties": {
"lots": 4,
"of": 5,
"values" : 6
}
},
"AAD76465": {
"Type": "that",
"Properties": {
"lots": 7,
"of": 8,
"values" : 9
}
}
}
}
The goal is to add an element to the Properties node of any TopB child where .Type == "that". And the kicker is that I need to put the child node's key into the new element value with an added prefix.
So essentially I need the last element to look like this:
"AAD76465": {
"Type": "that",
"Properties": {
"lots": 7,
"of": 8,
"values": 9,
"newElement": "Prefix-AAD76465"
}
}
I also need to retain the whole rest of the file (or a new file for that matter). So I don't need a query but really a jq call to manipulate the existing file. Parallel to TopB there could be other elements that I'd still need in the file. And no, I don't know, neither do I have control over the naming of the children of TopB. All I have is that my targets are nested children of TopB with .Type == "that". There can be multiple of those.
Thanks for looking.
If you get the path to where you will be adding the new field first, you can simply extract the parent key from that.
reduce path(.TopB[] | select(.Type == "that") .Properties.newElement) as $p (.; setpath($p; "Prefix-\($p[1])"))
Online demo
Here'a solution that uses walk/1 and is therefore perhaps quite intuitive:
walk(if (type == "object") and .TopB
then .TopB |= with_entries(
.key as $key
| if .value.Type == "that"
then .value.Properties += { newElement: ("Prefix-" + $key) }
else . end)
else . end)
One advantage of this solution is that it meets the stated requirement:
The goal is to add an element to the Properties node of any TopB child ...
in the sense that no assumptions are made about the locations of objects with the "topB" key.
I want to extract value from dynamic JSON.
This generation is different every time when is executed.
I need to get ex: XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=
which is generated in the different location in the Json file, with different value
I tried with.
$.payload[?(#.eventType == 'AAA')].entityId
which is working fine.
But, i want more stronger query.
Is it possible to use && statement with the query something like:
$.payload[?(#.eventType == 'AAA')&&(#.outgoingCurrency== 'EUR')].entityId
My payload:
{
"payload":[
{
"entityId":"qvr_IlDhTdzldeccxguNR84sE0N78DUfNGzwH-3pY7Y=",
"accountHolderId":"dvwxpTxVHdo2n1d5ytO6WyhnI2nuaEuzsh47agPpSFU=",
"processorType":"DUMMY",
"eventType":"AAA",
"outgoingCurrency":"USD",
"holdPeriodInHours":11,
"disabled":false
},
{
"entityId":"XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=",
"accountHolderId":"Xoo8uAM90qRT7kceDUJBIIqafUuUdH2fH_Ia2z1TY5w=",
"processorType":"DUMMY",
"eventType":"BBB",
"outgoingCurrency":"EUR",
"holdPeriodInHours":10,
"disabled":false
},
{
"entityId":"yBoHvYkyszaQpaFe1zvqCY416_vYiq7iivA9bWJhiTg=",
"processorType":"BMO_CPR",
"eventType":"AAA",
"disabled":false
}
]
}
You need to use the operation && inside the expression:
$.payload[?(#.outgoingCurrency== 'EUR' && #.eventType == 'AAA')].entityId.
For more details see: https://goessner.net/articles/JsonPath/
I am trying to create a Json Extractor and it`s being a thought activity. I have this json structure:
[
{
"reportType":{
"id":3,
"nomeTipoRelatorio":"etc etc etc",
"descricaoTipoRelatorio":"etc etc etc",
"esExibeSite":"S",
"esExibeEmail":"S",
"esExibeFisico":"N"
},
"account":{
"id":9999999,
"holdersName":"etc etc etc",
"accountNamber":"9999999",
"nickname":null
},
"file":{
"id":2913847,
"typeId":null,
"version":null,
"name":null,
"format":null,
"description":"description",
"typeCode":null,
"size":153196,
"mimeType":null,
"file":null,
"publicationDate":"2018-12-05",
"referenceStartDate":"2018-12-05",
"referenceEndDate":"2018-12-06",
"extension":null,
"fileStatusLog":{
"idArquivo":2913847,
"dhAlteracao":"2018-12-05",
"nmSistema":"SISTEMA X",
"idUsuario":999999,
"reportStatusIndicador":"Z"
}
}
}
]
What I need to do: First of all, I am using the option "Compute concatenation var" and "Match No." as -1. Because the service can bring in the response many of those.
I have to verify, if "reportStatusIndicador" = 'Z' or 'Y', if positive, I have to collect File.Id OR file.FileStatusLog.idArquivo, they are the same, I was trying the first option, in this case the number "2913847", but if come more results, I will collect all File.id`s
With this values in hands, I will continue with a for each for all File.id`s.
My last try, was this combination, after reading a lot and tried many others combinations.
[?(#...file.fileStatusLog.reportStatusIndicador == 'Z' || #...file.fileStatusLog.reportStatusIndicador == 'Y')].file.id
But my debug post processor always appears like this, empty:
filesIds=
Go for $..[?(#.file.fileStatusLog.reportStatusIndicador == 'Z' || #.file.fileStatusLog.reportStatusIndicador == 'Y')].file.id
Demo:
References:
Jayway JsonPath: Inline Predicates
JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios
I could do it with this pattern:
[?(#.file.fileStatusLog.reportStatusIndicador == 'Z' ||
#.file.fileStatusLog.reportStatusIndicador == 'Y')].file.id
filesIds_ALL=2913755,2913756,2913758,2913759,2913760,2913761,2913762,2913763,2913764,2913765,2913766,2913767,2913768,2913769,2913770
//Please excuse my poor English.
Hello everyone, I am doing a project which is about a facebook comment spider.
then I find the Facebook Graph GUI. It will return a json file that's so complicated for me.
The json file is include so many parts
then I use json.loads to get all the json code
finally it return a dict for me.
and i dont know how to access the Value
for example i want get all the id or comment.
but i can only get the 2 key of dict "data" and "pading"
so, how can i get the next key? like "id" or "comment"
and how to process this complicated data.
code
Thank you very much.
Two ways I can think of, either you know what you're looking for and access it directly or you loop over the keys, look at the value of the keys and nest another loop until you reach the end of the tree.
You can do this using a self-calling function and with the appropriate usage of jQuery.
Here is an example:
function get_the_stuff(url)
{
$.getJSON(url, function ( data ) {
my_parser(data) });
}
function my_parser(node)
{
$.each(node, function(key, val) {
if ( val && typeof val == "object" ) { my_parser(val); }
else { console.log("key="+key+", val="+val); }
});
}
I omitted all the error checking. Also make sure the typeof check is appropriate. You might need some other elseif's to maybe treat numbers, strings, null or booleans in different ways. This is just an example.
EDIT: I might have slightly missed that the topic said "Python"... sorry. Feel free to translate to python, same principles apply.
EDIT2: Now lets' try in Python. I'm assuming your JSON is already imported into a variable.
def my_parser(node, depth=0):
if type(node) == "list":
for val in node:
my_parser(val,depth+1)
elif type(node) == "dict":
for key in node:
printf("level=%i key=%s" % ( depth, key ))
my_parser(node[key], depth+1)
elif type(node) == "str":
pritnf("level=%i value=%s" % ( depth, node ))
elsif type(node) == "int":
printf("level=%i value=%i % ( depth, node ))
else:
printf("level=%i value_unknown_type" % ( depth ))