Does the script filter expression in JSONPath applies only to array elements (and not objects)? - jsonpath

I have gone through most of the JSONPath documentations out there and they all explain that the script filters such as $.items[(#.length - 1)] only applies to an array and not to a JSON object. This means that the path would work for the first JSON object below and not for the second one:
1:
{
"items": [
1,
2
]
}
2:
{
"items": {
"item1": 1,
"item2": 2
}
}
Can anyone confirm this? Also, if I am correct, is there a logical reason for this behavior? I can imagine that such a path could have been allowed to return the same value (2) in both cases.

Related

JSONPath - Filter expression to print a field if an array contains a string

I have the following JSON and am trying to write a JSON Path expression which will return me the isbn number when I have a id of either '123456789' or '987654321'. I tried the following but this did not work. Can anybody tell me what I am doing wrong please. Thanks in advance
JSON Path Expression
$.books[?(#.ids== '123456789' )].isbnNumber
JSON
{
"books": [{
"title": "10",
"isbnNumber": "621197725636",
"ids": [
"123456789",
"987654321"
]
}]
}
The (more traditional) JSONPath implementations that stick close(r) to Goessner's reference specification do not offer handy functions like in which are available in extended implementations like JayWay's JSONPath.
Using Gatling's JSONPath, one thing we could do if the positions of the Ids in question are fixed is accessing their respective indices directly to make the comparison:
$.books[?(#.ids[0] == "123456789" || #.ids[1] == "987654321")].isbnNumber
This will give you the desired result of your example; however, some books only have one of the two indices, or they Id to compare to shows up on a different position it won't work.

JQ: remove nested key and keep other main array key intact

I have a json file looking like this:
{
"parents": [{
// array of objects
}],
"modules": {
"a": 1,
"b": 2
}
}
I want to remove they key b of the object modules.
I am running this command: jq "with_entries(.value |= del(.b))"
But this fails when the parents array is present. I get
Cannot index array with string "b"
How can I make the command ignore the parents array and only work on the modules object?
Your idea was right, but you missed the selecting the object desired inside with_entries(), hence your delete operation was attempted on all the objects in your JSON.
Since the parents record is an array type and not an object , the del function throws out an error that its not able to index the array with the given name. You need to do
with_entries( select(.key == "modules").value |= del(.b) )
The select() function filters that object keyed by name "modules" and applies the delete action on that object alone.
jq-play snippet

Add element to arrays, that are values to a given key name (json transformation with jq)

I'm a jq newbie, and I try to transform a json (a Swagger spec). I want to add an element to the array value of the "parameter" keys:
{
...
"paths": {
"/great/endpoint1": {
"get": {
"parameters": [] <<--- add a value here
}
}
"/great/endpoint2": {
"post": {
"parameters": [] <<-- and here too here too etc.
....
The following jqplay almost works. It adds values to the right arrays, but it has the nasty side effect of also removing the "x-id" value from the root of the input json. It's probably because of a faulty if-condition. As the paths contain a varying string (the endpoint names), I don't know how to write a wildcard path expression to address those, which is why I have tried using walk instead:
https://jqplay.org/s/az56quLZa3
Since the sample data is incomplete, it's difficult to say exactly what you're looking for but it looks like you should be using parameters in the call to walk:
walk(if type=="object" and has("parameters")
then .parameters += [{"extra": "value"}]
else . end)
If you want to restrict the walk to the top-level paths, you would preface the above with: .paths |=

Can predicate values have wildcards in Mountebank?

I am trying to define a stub:
{
"predicates":[
{
"equals":{
"method":"GET",
"path":"/sword/eBISXMLInvoice2.do",
"query": {
"action": "index",
"page": 3 <-- this one!
}
}
}
],
"responses":[
{
"is":{
"statusCode":200,
"headers":{
"Content-Type":"application/xml"
},
"body":"<doclist><document uuid='101654' type='invoice' date='2018-11-14 13:49:43' /></doclist>"
}
}
]
}
One of the expected query string parameters (called "page") can have multiple values. How can I define the predicate to handle this?
My question is actually very easy to answer. According to the docs, the "equals" predicate, will match if any value matches.
Full text:
On occasion you may encounter multi-valued keys. This can be the case
with querystrings and HTTP headers that have repeating keys, for
example ?key=first&key=second. In those cases, deepEquals will
require all the values (in any order) to match. All other predicates
will match if any value matches, so an equals predicate will match
with the value of second in the example above.
So I can just remove the changeable query string value from the predicate, or I can keep it in there, it doesn't matter.
{
"equals":{
"method":"GET",
"path":"/sword/eBISXMLInvoice2.do",
"query": {
"action": "index"
}
}
}

MapReduce for counting parameter values

I have document like this:
{
"_id": ObjectId("4d17c7963ffcf60c1100002f"),
"title": "Text",
"params": {
"brand": "BMW",
"model": "i3"
}
}
{
"_id": ObjectId("4d17c7963ffcf60c1100002f"),
"title": "Text",
"params": {
"brand": "BMW",
"model": "i5"
}
}
What i need is the count of every params values. like:
brand
---------
BMW (2)
model
---------
i3 (1)
i5 (1)
I think i have to write map/reduce functions. How can i do this? Thanks.
I think i have to write map/reduce functions.
Yes you need a map-reduce for this. For some simple map-reduce examples, please look here.
For your particular case, you first need to change your expectation of the output. The output of the map / reduce is a collection. The collection will look (in your case) something like this:
{ key : { 'brand' : 'bmw' }, value : 2 }
{ key : { 'model' : 'i5' }, value : 1 }
To generate this set you will need a "map" function and a "reduce" function. The "map" function will emit a key and a value. The key is each element of params, the value is the count of 1. The "reduce" function accepts a key and an array of values and returns just a single value. Your question is basically the same as this example on the MongoDB site:
map = function() {
if (!this.params) {
return;
}
for (index in this.params) {
emit(this.params[index], 1);
}
}
reduce = function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}
In your map function enumerate the properties of the params property of the this object. For each property you find call emit with a key that contains both the name of the property and the value of the property. Pass 1 as the value. e.g. emit({'brand','BMW'}, 1) but obviously using variables not constants!
In your reduce function you are passed a key and an array of values. Sum these values and return the sum. Even though the initial array will be all 1's don't be tempted to use the length of the array because the reduce function can be called iteratively.
You can group the results afterwards from the result collection, applying an index if necessary for performance.

Resources