I have struggles to craft working jsonpath (Jayway https://jsonpath.herokuapp.com/) where property (scalar) is returned as array.
For input
{
"a":{
"b":"valueofb"
}
}
I would like obtain array: ["valueofb"] NOT just valueofb
I have found an option how to do it.
$..a.b
Related
With JSONPath, how can you extract a single value from a list of known keys?
For example, I want to write one JSON path expression that can extract Sean from all three of these JSON documents:
{ "firstName": "Sean" }
{ "first_name": "Sean" }
{ "first_name": "Sean", "firstName": "Sean" }
This example is a little contrived, but I have an actual use case that requires this behavior.
The best I can come up with is the expression $.firstName,first_name which will work for #1 and #2 but returns an array for #3 — and I just want the first value that matches.
Basically, I’m looking for a JSONPath extract expression that simulates this JavaScript code:
json.firstName || json.first_name
I believe you want something like below :)
You can get json path using the index .Whn I'm using rest-assured I always use something similar to below code to extract values from my json response .
Response response=given().contentType(ContentType.JSON).get("http://localhost:3000/posts");
JsonPath jsonPathEvaluator = response.jsonPath();
String fn1 = jsonPathEvaluator.get("firstName[0]");
String fn_1=jsonPathEvaluator.get("first_name[0]");
String fn2=jsonPathEvaluator.get("firstName[1]");
You can pass all pair to dict and then extract your values or if you need only values you can use set structure to store keys and separate list to values.
I have incoming param List<Somedata>.Somedata class contains id field.
My goal is to make HashMap<Somedata.id, Somedata> from this list.
Is next approach correct or there is a better/safer way to do that?
list
.filter { it.id != null }
.associateTo(HashMap(), {it.id!! to it})
Actually, I cannot understand, why should I use !! keyword in associateTo method, when above I filtered it with non-null values only.
Or maybe there is a good way to perform this with ?. or ?.let keywords?
You can do:
list.mapNotNull { e -> e.id?.let { it to e } }.toMap()
Breakdown:
The call to .let with the ?. safe call operator will make the result null if the element is null.
So the lambda passed to mapNotNull is of type (Somedata) -> Pair<IdType, Somedata>.
mapNotNull discards the null pairs, and toMap turns the resulting List<Pair<IdType, Somedata>> into a Map<IdType, Somedata>.
If you want to avoid the creation of an intermediate list to hold the pairs, you can turn the list into a lazy Sequence from the start:
list.asSequence().mapNotNull { e -> e.id?.let { it to e } }.toMap()
Alternatively, since you asked:
why should I use !! keyword in associateTo method, when above I filtered it with non-null values only.
this is because the list is still of type List<Somedata> - this says nothing about the nullability of the field itself. The compiler does not know that the id fields are still not null, by the time your associateTo call is executed.
I'm using PHPUnit to auto-test my app. I want to assert the result of a function call which can return a boolean or a string. My code looks like this:
$myExample = new MyExample();
$value = $myExample->getValue();
if ($value !== false) {
assertNotNull($value);
assertFalse(empty($value));
}
But is it also possible to check whether the method executes successfully? Is "assertTrue($value)" the correct way?
UPDATE: Deprecated methods
Please use the following ones in case you want to check the data type:
assertIsArray()
assertIsBool()
assertIsFloat()
assertIsInt()
assertIsNumeric()
assertIsObject()
assertIsResource()
assertIsString()
assertIsScalar()
assertIsCallable()
assertIsIterable()
assertIsNotArray()
assertIsNotBool()
assertIsNotFloat()
assertIsNotInt()
assertIsNotNumeric()
assertIsNotObject()
assertIsNotResource()
assertIsNotString()
assertIsNotScalar()
assertIsNotCallable()
assertIsNotIterable()
UPDATE: As per mtiziani's comment below, this answer applies for PHPUnit versions below 9.#
If you want to assert the data type of the value, the correct way would be:
$this->assertInternalType('[expected_data_type]', $value);
The [expected_data_type] PHPUnit can validate can be any of these:
'array'
'boolean'
'bool'
'float'
'integer'
'int'
'null'
'numeric'
'object'
'resource'
'string'
'scalar'
'callable'
So, to assert that the returned value is a boolean, you would:
$this->assertInternalType('bool', $value);
You can use:
$this->assertSame($expect, $actual)
It will test for type and value (i.e. $expected===$actual).
If you want to test if the function returns false for certain data then you might consider doing that in a separate test method. The same with testing for a string. If you test for one value type at a time, the asserts are less complicated. Some people consider it to be good unit testing practice to have one assert per test method.
$this->assertFalse( $returnVal );
$this->assertInternalType('string', $returnValue);
I have a JSON object say:
Json::Value temp;
temp["example1"] = "first";
which will be represented as
{
"example1" : "first"
}
Now if I want to add another object into the above object without using the index method, how can I do it? For example:
{
"example1" : "first",
"example2" : "second"
}
but avoiding using syntax
temp["example2"] = "second";
Are there any equivalents to push_back() (like in C++ vector/list) in JsonCpp?
The equivalent to push_back in JsonCpp is append, but you can use it only on Json::nullValue or Json::arrayValue.
That makes sense because only one parameter is needed to add an element to an array.
What are you asking is unclear/not possible, because you are trying to create an object, which is like a std::map in C++, and two parameters are needed to insert an element here.
Not sure if this makes sense, but I need to check if a server value returned is actually a number. Right now I get ALL number values returned as strings
ie '7' instead of 7.
What's the simplest way to check if string values can actually be converted to numbers?
The easiest way to do this is to actually convert the string to a Number and test to see if it's NaN. If you look at the Flex API reference, the top-level Number() function says it will return NaN if the string passed to the method cannot be converted to a Number.
Fortunately, Flex (sort of) does this for you, with the isNaN() function. All you need to do is:
var testFlag:Boolean = isNaN( someStringThatMightBeANumber );
If testFlag is false, the string can be converted to a number, otherwise it can't be converted.
Edit
The above will not work if compiling in strict mode. Instead, you will need to first convert to Number and then check for NaN, as follows:
var testFlag:Boolean = isNaN( Number( someStringThatMightBeANumber ) );
Haven't tested this, but this should work:
if( isNaN(theString) ) {
trace("it is a string");
} else {
trace("it is a number");
}
If you are using AS3 and/or strict mode (as pointed out by back2dos), you will need to convert to number first in order for it to compile:
if( isNaN(Number(theString)) ) {
trace("it is a string");
} else {
trace("it is a number");
}
Most of the answers on this question have a major flaw in them. If you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number". Try something like this instead:
function isANumber( val:* ):Boolean {
return !(val === null || val === "" || isNaN(val));
}
RegExp path :
function stringIsAValidNumber(s: String) : Boolean {
return Boolean(s.match(/^[0-9]+.?[0-9]+$/));
}
Here is another way to check if value can be converted to a number:
var ob:Object = {a:'2',b:3,c:'string'};
for( var v:* in ob){
var nr:Number = ob[v];
trace(ob[v]+" "+(nr === Number(nr)))
}
this will trace following:
2 true
3 true
string false
You can notice that in actionscript :
trace(int('7')); // will return 7
and
trace(int('a')); // will return 0
So except for zeros, you can actually now if a string is a number or not
this will try to convert your String to a Number, which essentially is a 64 bit floating point number:
var val:Number = Number(sourceString);
if sourceString is not a valid String representation of a Number, val will be NaN (not a number) ... you have check against that value with isNaN ... because val == NaN will return false for a reason that can't quite understand ... you can use int(val) == val to check, whether it is an integral value ...
greetz
back2dos
Put this into any function where you want only numbers to stayjoy_edit1 is a TextInput Object (spark)
//is a number check
if( isNaN(Number(joy_edit1.text)) ) {
joy_edit1.text = "";
return void;
}
function isANumber(__str:String):Boolean
{
return !isNaN(Number(__str));
}
You should use the native solution of Adobe:
parseInt and parseFloat methods.
Also read the isNaN description:
Returns true if the value is NaN(not a number). The isNaN() function
is useful for checking whether a mathematical expression evaluates
successfully to a number. The most common use of isNaN() is to check
the value returned from the parseInt() and parseFloat() functions. The
NaN value is a special member of the Number data type that represents
a value that is "not a number."
Here is a simple implementation:
function isANumber(value:String):Boolean {
return !isNaN(parseFloat(value));
}
typeof('7') == 'string'
typeof(7) == 'number'
Does that help?