How to concatenate json result elements with JsonPath (JayWay) - json

I have this JSON response:
{
"agreedToTermsOfUse": true,
"firstName": "Admin",
"lastName": "iConsulto",
"middleName": "",
"status": 0,
"timeZoneId": "UTC",
}
and I am trying to concatenate the first name and the last name.
I have tried to do this:
$..concat($..firstName," ",$..lastName)
but it returns me an empty value.
I have also try this:
$..concat("+",$..lastName)
And it has returned me this:
+["lastNameUser"]
Any ideas about why the second one option returns me something (like a list) and the first one doesn't return anything??
I have tried also this:
$..concat("+",$..lastName[0])
but it doesn't return me just the last name with the plus symbol.
So... How I can concatenate both names?? Thanks in advance!!!

Do not use deep scan .. operator while concatenating.
Try the below jsonpath-expression
$.concat($.firstName," ",$.lastName)
Online Tool : https://jsonpath.herokuapp.com/

Related

Is there a function in MYSQL like JSON_ARRAY_APPEND but for multiple vaues to be appended?

I'm wanting to add multiple values in JSON_ARRAY_APPEND.
For example in the following query:
SET #data = '{
"Person": {
"Name": "Homer",
"Hobbies": ["Eating", "Sleeping"]
}
}';
SELECT JSON_ARRAY_APPEND(#data, '$.Person.Hobbies', "Base Jumping") AS 'Result';
Our result would be:
{"Person": {"Name": "Homer", "Hobbies": ["Eating", "Sleeping", "Base Jumping"]}}
I'd like to be able to add multiple hobbies in one line rather than a dozen, using something like
SET #data = '{
"Person": {
"Name": "Homer",
"Hobbies": ["Eating", "Sleeping"]
}
}';
SELECT JSON_ARRAY_APPEND(#data, '$.Person.Hobbies', '"Base Jumping","Skiing"') AS 'Result';
Which results in
{"Person": {"Name": "Homer", "Hobbies": ["Eating", "Sleeping", "\"Base Jumping\",\"Skiing\""]}}
That's almost what I want but has extra characters that aren't wanted. Is there a better way to go about this?
JSON_ARRAY_APPEND() allows you to specify multiple path and value arguments. You can repeat the same path, and it will append to the result of the preceding append.
SELECT JSON_ARRAY_APPEND(#data,
'$.Person.Hobbies', "Base Jumping",
'$.Person.Hobbies', "Skiing") AS Result;
This is mentioned in the documentation:
The path-value pairs are evaluated left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
You can also use JSON_MERGE_PRESERVE() to concatenate arrays:
SELECT JSON_MERGE_PRESERVE(#data, '$.Person.Hobbies', '["Base Jumping", "Skiing"]') AS Result;

jsonPath - how to filter results by matching substring

I have a structure like this:
{"payload": {
"Item1": {
"property1": "Sunday",
"property2": "suffering_8890"
},
"Item2": {
"property1": "Monday",
"property2": "misery_0776"
},
"Item3": {
"property1": "Tuesday",
"property2": "pain_6756"
}
}
}
I need the property2 value that contains a certain sub-string (i.e- "misery"). Ultimately I just need the 4-digit code, but even getting the full value will work. I am able to get a list of all the property2 values by using:
$..property2
This returns:
Result[0] = suffering_8890
Result[1] = misery_0776
Result[2] = pain_6756
How do I filter it so that it only gives me the result containing the substring "misery"?
With regards to full value you can use a Filter Operator like:
$..[?(#.property2 =~ /misery.*?/i)].property2
Demo:
You can extract the 4-digit value out of the variable using Regular Expression Extractor
If you want to do this in one shot:
Add JSR223 PostProcessor as a child of the request which returns above JSON
Put the following code into "Script" area
vars.put('misery', ((com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..[?(#.property2 =~ /misery.*?/i)].property2').get(0) =~ ('(\\d+)'))[0][1]))
Refer the extracted value as ${misery} where required
More information: Apache Groovy - Why and How You Should Use It
You can use a regular expression extractor as well for the mentioned scenario to fetch the four-digit as below
property2": "misery_(.*)"
This will help you to save the four-digit code in JMeter variables right away. If you insist you to find out the required value from JSON using jsonpath, you can use JSON filter as below :-
$..[?(#.property2.indexOf('misery')>=0)]..property2

How do I access this JSON API data in Ruby?

I am writing a short Ruby program that is going to take a zipcode and return the names of cities within 2 miles of that zipcode. I successfully called an API and was able to parse the JSON data, but I'm unsure how to access the 'city' key.
url = API call (not going to replicate here since it requires a key)
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
Here's what my JSON looks like.
{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}
I've been trying to access 'city' like this:
response['result'][0]['city']
This appears to be incorrect. Also tried
response[0][0]['city']
And a couple of other permutations of the same code.
How can I get the value 'Northfield' out of the JSON data?
You're almost there, just use results instead of result on the result of JSON.parse(response) instead of on response:
JSON.parse(response)["results"][0]["city"]
#=> "Northfield"
JSON parse will create a hash then you can target the results which is an array of hashes, like so:
hash = JSON.parse(response)
hash['results'].select{|h| h['city'] == 'Northfield'}
Or if you only care about the results:
array = JSON.parse(response)['results']
array.select{|a| a['city' == 'Northfield'} #
To get just a single data point from the data, you might select one item in the array and then the key of the value you want:
array[0]['city']
For all the cities
cities = array.map{|k,v| k['city']}
You have a typo error, instead of response['result'] you can use it like response[:results].
And if you want to get the value of city key from all the hash, then response['result'][0]['city'] will not work.
After parsing response you will get an array of hashes, i.e
[{:zip=>"08225", :city=>"Northfield", :county=>"Atlantic", :state=>"NJ", :distance=>"0.0"}, {:zip=>"08221", :city=>"Linwood", :county=>"Atlantic", :state=>"NJ", :distance=>"1.8"}]
And if you want to fetch the values of key city from all the hash then you can try this steps
response[:results].map{|x| x[:city]}
which will give the result
["Atlantic", "Atlantic"]

Query a JSON column with an array of object in MySQL

I have a json column with the follow array:
[
{
"id": "24276e4b-de81-4c2c-84e7-eed9c3582a31",
"key": "id",
"type": "input",
},
{
"id": "e0ca5aa1-359f-4460-80ad-70445be49644",
"key": "name",
"type": "textarea",
}
]
I tried the follow query to get the row that has the id 24276e4b-de81-4c2c-84e7-eed9c3582a31 in the document column, but it returns not results:
select * from jobs WHERE document->'$[*].id' = "24276e4b-de81-4c2c-84e7-eed9c3582a31"
Anyone know how to do the right query?
I use mysql 5.7 and so JSON_CONTAINS can be easily used like this:
SELECT JSON_CONTAINS(
'[{"id": "24av","name": "she"},{"id": "e0c2", "name": "another_she"}]',
JSON_OBJECT('id', "e0c2")
);
Try like this:
SELECT * FROM jobs WHERE document->'$[*].id' = json_array("24276e4b-de81-4c2c-84e7-eed9c3582a31");
It works for me, but I think the below way is more better:
SELECT * FROM jobs WHERE json_contains(document->'$[*].id', json_array("24276e4b-de81-4c2c-84e7-eed9c3582a31"));
Actually It's easy just remember the return value is JSON_TYPE but not a String or something else;
maybe this? #Barmar
SELECT * FROM jobs WHERE JSON_SEARCH(document, "one", "24276e4b-de81-4c2c-84e7-eed9c3582a31", NULL, '$[*].id') IS NOT NULL;
When you use document->'$[*].id' it returns a comma-delimited list of all the ID properties. This won't be equal to the value of just one ID string, unless there's only one object in the document column.
You need to use JSON_SEARCH() to search for a matching element within the JSON value.
SELECT *
FROM jobs
WHERE JSON_SEARCH(document, "one", "24276e4b-de81-4c2c-84e7-eed9c3582a31", NULL, '$[*].id');

Yahoo YQL API - How to select a JSON field whose name is a reserved YQL keywords?

For example, I got following JSON from a URL
{ "time": "2014-05-10 06:23:36 UTC",
"values": [
{
"time_timetable_utc": "2014-05-10T06:25:00Z",
"time_realtime_utc": null,
"flags": ""
},
{
"time_timetable_utc": "2014-05-10T06:45:00Z",
"time_realtime_utc": null,
"flags": ""
},
]
}
This will work on YQL
select time from json where url="{url}"
It will return me only time field
{"time": "2014-05-10 06:23:36 UTC"}
But if I only want to get "values" array field with following
select values from json where url="{url}"
I will get this error message
Query syntax error(s) [line 1:7 expecting fields_or_star got 'values']
Just want to ask is that possible to select a JSON field whose name is a reserved Yahoo YQL keywords?
I know this will work
select * from json where url="{url}" and itemPath="json.values"
But is that possible to do it without using "itemPath" condition?
How to escape reserved word like "values" in YQL select?
Just want to ask is that possible to select a field names "values"?
No. (Sorry!)