Json_value and Json_query cannot find specified path - sql

I am trying to parse data from the following JSON. I know there are differences between JSON_VALUE and JSON_QUERY but I am trying to just get the path structure correct. I am using the STRICT option to validate my path's and so far other then string$ for JSON Query everything fails by not finding the path. As soon as I add the .data.taskData the path seems to blow up. Any help would be greatly appreciated.
I am setting the following JSON to #json
declare #json nvarchar(max)
SELECT JSON_VALUE(#json, 'strict$.data.taskData.startedLocation') as json
select JSON_QUERY(#json, 'strict$.data.taskData.startedLocation') as json
Below is the JSON I am trying to parse
{"data.taskData":{"startedAtUtc":"2019-08-28T20:21:29.025Z","startedLocation":{"lat":60.7348366,"lon":-124.9856841},"additionalData":[],"bols":[{"number":"1234","product":{"id":"COFFEE","description":"GROUND COFFE 5LB CAN","plannedQuantity":1352,"uom":"PCS","supplier":"WALMART ","accountOf":"","class":"UNKNOWN","loadedQuantity":6600,"netQuantity":9993},"net":"9993"}],"compartments":[{"id":"1","capacity":3400,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"1","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1000","bol":"1234"}],"loadedQuantity":1000,"productID":"COFFEE"},{"id":"2","capacity":2000,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"2","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2000","bol":"1234"}],"loadedQuantity":2000,"productID":"COFFEE"},{"id":"3","capacity":1100,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"3","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1100","bol":"1234"}],"loadedQuantity":1100,"productID":"COFFEE"},{"id":"4","capacity":2700,"commodity":null,"consignee":null,"plannedQuantity":0,"tankID":"4","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2500","bol":"1234"}],"loadedQuantity":2500,"productID":"COFFEE"}],"detention":{"minutes":null,"reasonCode":null,"notes":null},"initialCompartments":[{"id":"1","capacity":3400,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"1"},{"id":"2","capacity":2000,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"2"},{"id":"3","capacity":1100,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"3"},{"id":"4","capacity":2700,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"4"}],"loadingComplete":"yes","loadingCompleteTime":"2019-08-28T20:23:05.453Z","uom":{"key":"PCS","category":"volume","shortDisplay":"p","longDisplay":"Pieces","conversionFactors":{"gal":0.0625,"L":0.2365882365,"c":4.2267528377}},"variances":[],"completedAtUtc":"2019-08-28T20:23:06.703Z","completedLocation":{"lat":61.7348308,"lon":-124.9856879},"finalCompartments":[{"id":"1","capacity":3400,"productID":"COFFEE","loadedQuantity":1000,"consignee":"KSUAC","tankID":"1"},{"id":"2","capacity":2000,"productID":"COFFEE","loadedQuantity":2000,"consignee":"KSUAC","tankID":"2"},{"id":"3","capacity":1100,"productID":"COFFEE","loadedQuantity":1100,"consignee":"KSUAC","tankID":"3"},{"id":"4","capacity":2700,"productID":"COFFEE","loadedQuantity":2500,"consignee":null,"tankID":"4"}]}}

Try this out. After the code I'll comment about the specialities:
DECLARE #json NVARCHAR(MAX)=N'{
"data.taskData": {
"startedAtUtc": "2019-08-28T20:21:29.025Z",
"startedLocation": {
"lat": 60.7348366,
"lon": -124.9856841
},
"additionalData": [],
"bols": [
{
"number": "1234",
"product": {
"id": "COFFEE",
"description": "GROUND COFFE 5LB CAN",
"plannedQuantity": 1352,
"uom": "PCS",
"supplier": "WALMART ",
"accountOf": "",
"class": "UNKNOWN",
"loadedQuantity": 6600,
"netQuantity": 9993
},
"net": "9993"
}
],
"compartments": [
{
"id": "1",
"capacity": 3400,
"commodity": null,
"consignee": "KSUAC",
"plannedQuantity": 0,
"tankID": "1",
"additionalData": [],
"allLoadsValid": true,
"complete": true,
"error": false,
"locked": false,
"loads": [
{
"isFirst": true,
"quantity": "1000",
"bol": "1234"
}
],
"loadedQuantity": 1000,
"productID": "COFFEE"
},
{
"id": "2",
"capacity": 2000,
"commodity": null,
"consignee": "KSUAC",
"plannedQuantity": 0,
"tankID": "2",
"additionalData": [],
"allLoadsValid": true,
"complete": true,
"error": false,
"locked": false,
"loads": [
{
"isFirst": true,
"quantity": "2000",
"bol": "1234"
}
],
"loadedQuantity": 2000,
"productID": "COFFEE"
},
{
"id": "3",
"capacity": 1100,
"commodity": null,
"consignee": "KSUAC",
"plannedQuantity": 0,
"tankID": "3",
"additionalData": [],
"allLoadsValid": true,
"complete": true,
"error": false,
"locked": false,
"loads": [
{
"isFirst": true,
"quantity": "1100",
"bol": "1234"
}
],
"loadedQuantity": 1100,
"productID": "COFFEE"
},
{
"id": "4",
"capacity": 2700,
"commodity": null,
"consignee": null,
"plannedQuantity": 0,
"tankID": "4",
"additionalData": [],
"allLoadsValid": true,
"complete": true,
"error": false,
"locked": false,
"loads": [
{
"isFirst": true,
"quantity": "2500",
"bol": "1234"
}
],
"loadedQuantity": 2500,
"productID": "COFFEE"
}
],
"detention": {
"minutes": null,
"reasonCode": null,
"notes": null
},
"initialCompartments": [
{
"id": "1",
"capacity": 3400,
"commodity": null,
"consignee": null,
"plannedQuantity": null,
"tankID": "1"
},
{
"id": "2",
"capacity": 2000,
"commodity": null,
"consignee": null,
"plannedQuantity": null,
"tankID": "2"
},
{
"id": "3",
"capacity": 1100,
"commodity": null,
"consignee": null,
"plannedQuantity": null,
"tankID": "3"
},
{
"id": "4",
"capacity": 2700,
"commodity": null,
"consignee": null,
"plannedQuantity": null,
"tankID": "4"
}
],
"loadingComplete": "yes",
"loadingCompleteTime": "2019-08-28T20:23:05.453Z",
"uom": {
"key": "PCS",
"category": "volume",
"shortDisplay": "p",
"longDisplay": "Pieces",
"conversionFactors": {
"gal": 0.0625,
"L": 0.2365882365,
"c": 4.2267528377
}
},
"variances": [],
"completedAtUtc": "2019-08-28T20:23:06.703Z",
"completedLocation": {
"lat": 61.7348308,
"lon": -124.9856879
},
"finalCompartments": [
{
"id": "1",
"capacity": 3400,
"productID": "COFFEE",
"loadedQuantity": 1000,
"consignee": "KSUAC",
"tankID": "1"
},
{
"id": "2",
"capacity": 2000,
"productID": "COFFEE",
"loadedQuantity": 2000,
"consignee": "KSUAC",
"tankID": "2"
},
{
"id": "3",
"capacity": 1100,
"productID": "COFFEE",
"loadedQuantity": 1100,
"consignee": "KSUAC",
"tankID": "3"
},
{
"id": "4",
"capacity": 2700,
"productID": "COFFEE",
"loadedQuantity": 2500,
"consignee": null,
"tankID": "4"
}
]
}
}';
--The query
SELECT FirstLevel.StartedAtUtc
,JSON_VALUE(FirstLevel.startedLocation,'$.lat') AS startedLocation_Lat
,JSON_VALUE(FirstLevel.startedLocation,'$.lon') AS startedLocation_Lon
,FirstLevel.additionalData
,FirstLevel.bols
,Sub_Compartments.id
,Sub_Compartments.capacity
,FirstLevel.loadingComplete
FROM OPENJSON(#json,'$."data.taskData"')
WITH(startedAtUtc DATETIME2
,startedLocation NVARCHAR(MAX) AS JSON
,additionalData NVARCHAR(MAX) AS JSON
,bols NVARCHAR(MAX) AS JSON
--compartments seems to be a 1:n related node
,compartments NVARCHAR(MAX) AS JSON
,loadingComplete NVARCHAR(10)
--and more
) FirstLevel
OUTER APPLY OPENJSON(FirstLevel.compartments)
WITH (id INT
,capacity INT
--more columns
) Sub_Compartments;
The idea in short:
Your JSON is a fully blown deeply nested structure with various data. Returnin the whole and everything would lead to a very redundant flat table. It will be a good idea to query this JSON with a question as narrow as possible.
As you were told already we can use one of these:
JSON_VALUE() to retrieve a scalar value from a given path. Nested JSON will be returned as a string type.
JSON_QUERY() to extract a fragment of the JSON and proceed with it as JSON
OPENJSON is needed to dive into a JSON with repeated elements in order to return the fragments as a derived set row-by-row. Very important is the WITH-clause, which allows to change OPENJSON's default output to a side-by-side of columns (similar to PIVOT).
In this case we can use OPENJSON to dive into the first level and return the objects found there. Some of them are scalar values and can be returned as a typed value, others are JSON objects. In this case we have to use NVARCHAR(MAX) as data type and we must sepcify AS JSON in order to proceed with the return values.
In your JSON the compartments are a 1:n related set. We can use a cascade of OPENJSON calls, using the fragment returned by the first as input and use another WITH-clause to extract the compartement's columns.
I hope, that this exampe will give you enough hints, that you can query any place of your JSON. Good luck!

This works:
select JSON_QUERY(#json, 'strict$."data.taskData".startedLocation') as json
SELECT JSON_VALUE(#json, 'strict$."data.taskData".startedLocation.lat') as json

You need to consider the following:
When you want to extract JSON object or scalar value and your path begins with a dollar sign $ or has special characters in the keys, you need to surround it with quotes ""
Function JSON_QUERY extracts an object or an array from a JSON string. If the value is not an object or an array, the result is NULL in lax mode and an error in strict mode.
Function JSON_VALUE extracts a scalar value from a JSON string. If the path points to not a scalar value, the result is NULL in lax mode and an error in strict mode
When you want to parse JSON string and get results as table, use OPENJSON table-valued function.
With your sample data, you may try the following example:
DECLARE #json nvarchar(max) = N'{"data.taskData":{"startedAtUtc":"2019-08-28T20:21:29.025Z","startedLocation":{"lat":60.7348366,"lon":-124.9856841},"additionalData":[],"bols":[{"number":"1234","product":{"id":"COFFEE","description":"GROUND COFFE 5LB CAN","plannedQuantity":1352,"uom":"PCS","supplier":"WALMART ","accountOf":"","class":"UNKNOWN","loadedQuantity":6600,"netQuantity":9993},"net":"9993"}],"compartments":[{"id":"1","capacity":3400,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"1","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1000","bol":"1234"}],"loadedQuantity":1000,"productID":"COFFEE"},{"id":"2","capacity":2000,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"2","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2000","bol":"1234"}],"loadedQuantity":2000,"productID":"COFFEE"},{"id":"3","capacity":1100,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"3","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1100","bol":"1234"}],"loadedQuantity":1100,"productID":"COFFEE"},{"id":"4","capacity":2700,"commodity":null,"consignee":null,"plannedQuantity":0,"tankID":"4","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2500","bol":"1234"}],"loadedQuantity":2500,"productID":"COFFEE"}],"detention":{"minutes":null,"reasonCode":null,"notes":null},"initialCompartments":[{"id":"1","capacity":3400,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"1"},{"id":"2","capacity":2000,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"2"},{"id":"3","capacity":1100,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"3"},{"id":"4","capacity":2700,"commodity":null,"consignee":null,"plannedQuantity":null,"tankID":"4"}],"loadingComplete":"yes","loadingCompleteTime":"2019-08-28T20:23:05.453Z","uom":{"key":"PCS","category":"volume","shortDisplay":"p","longDisplay":"Pieces","conversionFactors":{"gal":0.0625,"L":0.2365882365,"c":4.2267528377}},"variances":[],"completedAtUtc":"2019-08-28T20:23:06.703Z","completedLocation":{"lat":61.7348308,"lon":-124.9856879},"finalCompartments":[{"id":"1","capacity":3400,"productID":"COFFEE","loadedQuantity":1000,"consignee":"KSUAC","tankID":"1"},{"id":"2","capacity":2000,"productID":"COFFEE","loadedQuantity":2000,"consignee":"KSUAC","tankID":"2"},{"id":"3","capacity":1100,"productID":"COFFEE","loadedQuantity":1100,"consignee":"KSUAC","tankID":"3"},{"id":"4","capacity":2700,"productID":"COFFEE","loadedQuantity":2500,"consignee":null,"tankID":"4"}]}}'
SELECT
JSON_QUERY(#json, 'strict $."data.taskData".startedLocation') AS StartedLocation,
JSON_VALUE(#json, 'strict $."data.taskData".startedLocation.lat') as Lat,
JSON_VALUE(#json, 'strict $."data.taskData".startedLocation.lon') as Lon
SELECT *
FROM OPENJSON(#json, 'strict $."data.taskData".compartments') AS Compartments
Output:
----------------------------------------------------------------
StartedLocation Lat Lon
----------------------------------------------------------------
{"lat":60.7348366,"lon":-124.9856841} 60.7348366 -124.9856841
----------------
key value type
----------------
0 {"id":"1","capacity":3400,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"1","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1000","bol":"1234"}],"loadedQuantity":1000,"productID":"COFFEE"} 5
1 {"id":"2","capacity":2000,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"2","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2000","bol":"1234"}],"loadedQuantity":2000,"productID":"COFFEE"} 5
2 {"id":"3","capacity":1100,"commodity":null,"consignee":"KSUAC","plannedQuantity":0,"tankID":"3","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"1100","bol":"1234"}],"loadedQuantity":1100,"productID":"COFFEE"} 5
3 {"id":"4","capacity":2700,"commodity":null,"consignee":null,"plannedQuantity":0,"tankID":"4","additionalData":[],"allLoadsValid":true,"complete":true,"error":false,"locked":false,"loads":[{"isFirst":true,"quantity":"2500","bol":"1234"}],"loadedQuantity":2500,"productID":"COFFEE"} 5

Related

Select data from Json array MS SQL Server

I have to select data from Json like this:
[
{
"id": 10100,
"externalId": "100000035",
"name": "Test1",
"companyId": 10099,
"phone": "0738003811",
"email": "test#Test.com",
"mainAddress": {
"county": "UK",
"province": "test",
"zipCode": "01234",
"city": "test",
"street": "test",
"gln": "44,37489331;26,21941193",
"country": {
"iso2": "UK",
"iso3": "UK"
}
},
"active": false,
"main": true,
"stores": [
"Test"
],
"attributes": [
{
"attributeId": 1059,
"attributeName": "CH6 name",
"attributeExternalId": null,
"attributeValueId": 74292,
"attributeValueType": "MONO_LINGUAL",
"attributeValueEid": null,
"attributePlainValue": "Unknown"
},
{
"attributeId": 1061,
"attributeName": "BD",
"attributeExternalId": null,
"attributeValueId": 81720,
"attributeValueType": "MONO_LINGUAL",
"attributeValueEid": null,
"attributePlainValue": "Not assigned"
}
],
"daysSinceLastOrder": null
},
{
"id": 62606,
"externalId": "VL_LC_000190",
"name": "Test",
"companyId": 17793,
"phone": "44333424",
"email": "test#email.com",
"mainAddress": {
"firmName": "test",
"county": "test",
"province": "test",
"zipCode": "247555",
"city": "test",
"street": "test",
"gln": "44.8773851;23.9223518",
"country": {
"iso2": "RO",
"iso3": "ROU"
},
"phone": "07547063789"
},
"active": true,
"main": false,
"stores": [
"Valcea"
],
"attributes": [
{
"attributeId": 1042,
"attributeName": "Type of location",
"attributeExternalId": "TYPE_OF_DIVISION",
"attributeValueId": 34506,
"attributeValueType": "MONO_LINGUAL",
"attributeValueEid": "Small OTC (<40mp)",
"attributePlainValue": "Small OTC (<40mp)"
},
{
"attributeId": 17,
"attributeName": "Limit for payment",
"attributeExternalId": "LIMIT_FOR_PAYMENT_IN_DAYS",
"attributeValueId": 59120,
"attributeValueType": "NUMBER",
"attributeValueEid": null,
"attributePlainValue": "28"
}
],
"daysSinceLastOrder": 147
}
]
I know how to select data from simple json object using "FROM OPENJSON",
but now I have to select a
AttributeValueId, AttributeId and AttributeName, attributePlainValue and CompanyId for each Attribute. So I dont know how to select data from attributes array and then how to join to this CompanyId which is one level up.
Maybe someone knows how write this query.
As mentioned by #lptr in the comments:
You need to pass the result of one OPENJSON to another, using CROSS APPLY. You can select a whole JSON object or array as a property, by using the syntax AS JSON
select
t1.companyid,
t2.*
from openjson(#j)
with (
companyId int,
attributes nvarchar(max) as json
) as t1
cross apply openjson(t1.attributes)
with
(
attributeId int,
attributeName nvarchar(100),
attributeValueId nvarchar(100),
attributePlainValue nvarchar(100)
) as t2;
db<>fiddle
For example, you can use code like this.
f1.metaData->"$.identity.customerID" = '.$customerID.'

azure search exact match of file name not returning exact results

I am indexing all the file names into the index. But when I search with exact file name in the search query it is returning all other file names also. below is my index definition.
{
"fields": [
{
"name": "id",
"type": "Edm.String",
"facetable": true,
"filterable": true,
"key": true,
"retrievable": true,
"searchable": false,
"sortable": false,
"analyzer": null,
"indexAnalyzer": null,
"searchAnalyzer": null,
"synonymMaps": [],
"fields": []
},
{
"name": "FileName",
"type": "Edm.String",
"facetable": false,
"filterable": false,
"key": false,
"retrievable": true,
"searchable": true,
"sortable": false,
"analyzer": "keyword-analyzer",
"indexAnalyzer": null,
"searchAnalyzer": null,
"synonymMaps": [],
"fields": []
}
],
"scoringProfiles": [],
"defaultScoringProfile": null,
"corsOptions": null,
"analyzers": [
{
"name": "keyword-analyzer",
"#odata.type": "#Microsoft.Azure.Search.CustomAnalyzer",
"charFilters": [],
"tokenizer": "keyword_v2",
"tokenFilters": ["lowercase", "my_asciifolding", "my_word_delimiter"]
}
],
"tokenFilters": [
{
"#odata.type": "#Microsoft.Azure.Search.AsciiFoldingTokenFilter",
"name": "my_asciifolding",
"preserveOriginal": true
},
{
"#odata.type": "#Microsoft.Azure.Search.WordDelimiterTokenFilter",
"name": "my_word_delimiter",
"generateWordParts": true,
"generateNumberParts": false,
"catenateWords": false,
"catenateNumbers": false,
"catenateAll": false,
"splitOnCaseChange": true,
"preserveOriginal": true,
"splitOnNumerics": true,
"stemEnglishPossessive": false,
"protectedWords": []
}
],
"#odata.etag": "\"0x8D6FB2F498F9AD2\""
}
Below is my sample data
{
"value": [
{
"id": "1",
"FileName": "SamplePSDFile_1psd2680.psd"
},
{
"id": "2",
"FileName": "SamplePSDFile-1psd260.psd"
},
{
"id": "3",
"FileName": "SamplePSDFile_1psd2689.psd"
},
{
"id": "4",
"FileName": "SamplePSDFile-1psdxx2680.psd"
}
]
}
Below is the Analyze API results
{
"tokens": [
{
"token": "samplepsdfile_1psd2689.psd",
"startOffset": 0,
"endOffset": 26,
"position": 0
},
{
"token": "samplepsdfile",
"startOffset": 0,
"endOffset": 13,
"position": 0
},
{
"token": "psd",
"startOffset": 15,
"endOffset": 18,
"position": 1
},
{
"token": "psd",
"startOffset": 23,
"endOffset": 26,
"position": 2
}
]
}
When I search with the keyword "SamplePSDFile_1psd2689.psd", Azure search returning three records in the results instead of only document 3. Below is my search query and the results.
?search="SamplePSDFile_1psd2689.psd"&api-version=2019-05-06&$count=true&queryType=full&searchMode=All
{
"#odata.count": 3,
"value": [
{
"#search.score": 2.3387241,
"id": "2",
"FileName": "SamplePSDFile-1psd260.psd"
},
{
"#search.score": 2.2493405,
"id": "3",
"FileName": "SamplePSDFile_1psd2689.psd"
},
{
"#search.score": 2.2493405,
"id": "1",
"FileName": "SamplePSDFile_1psd2680.psd"
}
]
}
How I can achieve my expected results. I tried with and without double quotes around the keyword all other options, but no luck. What I am doing wrong here in this case?
Some body suggested to use $filter, but that field wasn't filterable in our case.
Please help me on this.
If you are looking for exact match then you probably don't want any analyzer involved. Give it a try with this line
"analyzer": "keyword-analyzer"
changed to
"analyzer": null
If you need to be able to do exact match on the field and also support partial keyword searches then you need to index the field twice with different names. Maybe append “Exact” to the exact match field name and don’t use an analyzer for that one. The name without exact can have an analyzer. Then search on the field using the right field name index depending on the type of search.

Deduplicate table SQL with nested rows (type STRUCT)

I have a SQL table (in BigQuery) with possible duplicated rows. The table has over 20 columns, some of them are nested (data type "STRUCT)". I want to deduplicate the table.
I can't simply query SELECT DISTINCT * because I get an error
Query error: Column options of type STRUCT cannot be used in SELECT DISTINCT
So far, I tried to create a unique ID based on a hash of certain columns.
I have now this unique ID (called sha256), but I can't figure out a way of selecting only rows with unique hash.
I tried to GROUP BY, but it doesn't work with STRUCT type, and I tried also to INNER JOIN with a table containing only unique hashed, but I get duplicates also.
For reference, here are 2 example rows of the dataset:
{
"sha256": "un2k3TUtzwzmQMvxfrjztsh/A/GW3WWzV4U4CezqceA=",
"has_phone": true,
"options": {
"sub_toplist": true,
"gallery": false,
"urgent": false,
"has_option": true,
"photosup": true,
"booster": false
},
"calendar": {
"dates": null
},
"owner": {
"siren": null,
"pro_rates_link": null,
"user_id": "f0d94687-1a24-4ed4-8adb-7faded053ca8",
"type": "private",
"no_salesmen": true,
"name": "marius",
"store_id": "5022456"
},
"location": {
"feature": {
"properties": null,
"geometry": {
"coordinates": [
"9.41733",
"42.54701"
],
"type": "Point"
},
"type": "Feature"
},
"is_shape": true,
"provider": "here",
"lng": "9.41733",
"lat": "42.54701",
"zipcode": "20290",
"city_label": "Lucciana 20290",
"city": "Lucciana",
"region_name": "Corse",
"department_name": null,
"source": "city",
"department_id": "0",
"region_id": "9"
},
"attributes": {
"pro_rates_link": null,
"immo_sell_type": "old",
"ges": "a",
"square": "92",
"rooms": "4",
"energy_rate": "b",
"is_import": false,
"custom_ref": null,
"lease_type": "sell",
"real_estate_type": "1",
"fai_included": null,
"type_real_estate_sale": null
},
"price_calendar": null,
"price": [
"270000"
],
"body": "text",
"url": "https://www.example.fr/ventes_immobilieres/1729537955.htm",
"category_name": "Ventes immobilières",
"category_id": "9",
"images": {
"urls_thumb": [
"https://img3.example.fr/ad-thumb/d63e236ce3546906b3ce661640a7cf858d0a0593.jpg"
],
"urls": [
"https://img3.example.fr/ad-image/ac6bd9ce0cc3aa507727ddece51f437d77ae4cfa.jpg",
],
"nb_images": "7",
"small_url": "https://img3.example.fr/ad-small/ac6bd9ce0cc3aa507727ddece51f437d77ae4cfa.jpg",
"thumb_url": "https://img3.example.fr/ad-thumb/ac6bd9ce0cc3aa507727ddece51f437d77ae4cfa.jpg"
},
"ad_type": "offer",
"first_publication_date": "2020-01-02 15:00:46 UTC",
"status": "active",
"subject": "Villa à Lucciana",
"index_date": "2020-01-16 15:00:45 UTC",
"expiration_date": "2020-03-02 15:00:46 UTC",
"list_id": "1729537955"
},
{
"sha256": "wCMrggkqSJ3PgbkuWAgBpCMtFfkJDRlz6TOeO5Nngsg=",
"has_phone": true,
"options": {
"sub_toplist": false,
"gallery": false,
"urgent": false,
"has_option": false,
"photosup": false,
"booster": false
},
"calendar": {
"dates": null
},
"owner": {
"siren": null,
"pro_rates_link": null,
"user_id": "ae0f432d-0aa2-4828-a20b-3472255588b4",
"type": "private",
"no_salesmen": true,
"name": "M.Milleliri",
"store_id": "12132533"
},
"location": {
"feature": {
"properties": null,
"geometry": {
"coordinates": [
"9.1917",
"41.54506"
],
"type": "Point"
},
"type": "Feature"
},
"is_shape": true,
"provider": "here",
"lng": "9.1917",
"lat": "41.54506",
"zipcode": "20146",
"city_label": "Sotta 20146",
"city": "Sotta",
"region_name": "Corse",
"department_name": null,
"source": "city",
"department_id": "0",
"region_id": "9"
},
"attributes": {
"pro_rates_link": null,
"immo_sell_type": "old",
"ges": "Non renseigné",
"square": null,
"rooms": null,
"energy_rate": "Non renseigné",
"is_import": false,
"custom_ref": null,
"lease_type": "sell",
"real_estate_type": "3",
"fai_included": null,
"type_real_estate_sale": null
},
"price_calendar": null,
"price": [
"100000"
],
"body": "text",
"url": "https://www.example.fr/ventes_immobilieres/1736199673.htm",
"category_name": "Ventes immobilières",
"category_id": "9",
"images": {
"urls_thumb": [
"https://img3.example.fr/ad-thumb/4f3632dc8e5c50075aa6c6e4b559e2042546f009.jpg"
],
"urls": [
"https://img3.example.fr/ad-image/4f3632dc8e5c50075aa6c6e4b559e2042546f009.jpg"
],
"urls_large": [
"https://img3.example.fr/ad-large/4f3632dc8e5c50075aa6c6e4b559e2042546f009.jpg"
],
"nb_images": "1",
"small_url": "https://img3.example.fr/ad-small/4f3632dc8e5c50075aa6c6e4b559e2042546f009.jpg",
"thumb_url": "https://img3.example.fr/ad-thumb/4f3632dc8e5c50075aa6c6e4b559e2042546f009.jpg"
},
"ad_type": "offer",
"first_publication_date": "2020-01-16 14:21:05 UTC",
"status": "active",
"subject": "Terrain 1250 m2 Sotta",
"index_date": "2020-01-16 14:21:05 UTC",
"expiration_date": "2020-03-16 14:21:05 UTC",
"list_id": "1736199673"
}
and the query I'm working on so far:
WITH
table_unique_hash AS (
SELECT
DISTINCT(SHA256(CONCAT(FORMAT_TIMESTAMP('%Y/%m/%d_%H:%M:%S_', index_date), CAST(list_id AS STRING)))) AS sha256
FROM
`test_bucket_data.daily_table`),
table_hashed AS (
SELECT
SHA256(CONCAT(FORMAT_TIMESTAMP('%Y/%m/%d_%H:%M:%S_', index_date), CAST(list_id AS STRING))) AS sha256, *
FROM
`test_bucket_data.daily_table`)
SElECT * FROM table_hashed
limit 10;
A solution would be to find a way of inner join the table_hashed and the table_unique_hash on the sha256 column...
Thanks for your help!
I found a workaround based on this topic. The combination of GROUP BY and ANY function for all the STRUCT columns made it work!
SELECT
has_phone,
ANY_VALUE(options) as options,
ANY_VALUE(calendar) as calendar,
ANY_VALUE(owner) as owner,
ANY_VALUE(location) as location,
ANY_VALUE(attributes) as attributes,
price_calendar,
price,
body,
url,
category_name,
category_id,
ANY_VALUE(images) as images,
ad_type,
first_publication_date,
status,
subject,
index_date,
expiration_date,
list_id,
FROM
`{table_name}`
Group by
has_phone,
price_calendar,
price,
body,
url,
category_name,
category_id,
ad_type,
first_publication_date,
status,
subject,
index_date,
expiration_date,
list_id
Note: my "price" field was previously an array; I transformed it in my source json to an int

Traversing JSON objects with tSQL - OPENJSON

I have the following JSON code. I pull the values into a SQL database using OPENJSON, but I am having trouble with the path for the Refund object.
I am trying to pull the "amount" value in the "transactions" object (so the expected value should be 298.47).
SQL code (currently returns only null values)
OPEN(json)
WITH(
OtherJSONstuff varchar '$otherjsonstuff'
Refund int '$.refund[0].transactions.amount' <what should this be
JSON Code
"otherjsonstuff": othervalues
"otherjsonstuff": othervalues
"object": [
{
"id": 212,
"items": [
{
"id": 151,
"quantity": 3,
"item_id": 926,
"subtotal": 30.0,
"tax": 0.0,
"item": {
"id": 926,
"quantity": 3,
"price": "10.00",
"product_id": 934,
"properties": [],
"discount": "0.00",
"tax": []
}
}
],
"action": [
{
"id": 537,
"amount": "298.47", --this is the line I need
"kind": "refund",
"created": "2016-12-13",
"location_id": null,
"parent_id": 537,
}
],
}
],
Having reformatted the JSON code,
it should be $.refund[0].transactions[0].amount
Depend on the array object you want to access, just increment and decrements the values. The root cause is understanding the JSON hierarchy and JNevil has provided you some good resources

Access subscription details with Stripes Webhooks PHP

I haven't been able to find any details for this with PHP, so I am hoping somebody can help me complete this script?
I am searching for the Subscription details from the Stripe API Webhook event. The event I am working on is invoice.payment_succeeded although I am struggling to access the subscription information from this. Here is the test event in full:
{
"id": "evt_19HdmRL346436RYAmvgxkr",
"object": "event",
"api_version": "2016-07-06",
"created": 1479580899,
"data": {
"object": {
"id": "in_19HdmRLniq434634643dO2gU",
"object": "invoice",
"amount_due": 700,
"application_fee": null,
"attempt_count": 1,
"attempted": true,
"charge": "ch_19Hdm3463464365IDDXX",
"closed": true,
"currency": "gbp",
"customer": "315464619",
"date": 1479580899,
"description": null,
"discount": null,
"ending_balance": 0,
"forgiven": false,
"lines": {
"object": "list",
"data": [
{
"id": "sub_9apRC346346CMNg",
"object": "line_item",
"amount": 700,
"currency": "gbp",
"description": null,
"discountable": true,
"livemode": false,
"metadata": {
"website_ref": "Z8ckRo2x",
"user_id": "1"
},
"period": {
"start": 1479580899,
"end": 1482172899
},
"plan": {
"id": "AdFree",
"object": "plan",
"amount": 700,
"created": 1479261871,
"currency": "gbp",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"name": "AdFree",
"statement_descriptor": "SNAPPYSITES ADFREE",
"trial_period_days": null
},
"proration": false,
"quantity": 1,
"subscription": null,
"type": "subscription"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/invoices/in_19HdmRLn34353465dO2gU/lines"
},
"livemode": false,
"metadata": {},
"next_payment_attempt": null,
"paid": true,
"period_end": 1479580899,
"period_start": 1479580899,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"subscription": "sub_9a2552OA5553MNg",
"subtotal": 700,
"tax": null,
"tax_percent": null,
"total": 700,
"webhooks_delivered_at": null
}
},
"livemode": false,
"pending_webhooks": 1,
"request": "req_9apRx9555ZVm55",
"type": "invoice.payment_succeeded"
}
I am currently listening with this unfinished script:
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
$event = \Stripe\Event::retrieve($event_id);
if($event->type == 'invoice.payment_succeeded'){
$invoice = $event->data->object;
$subscription = $invoice->lines->data->plan;
$customer = \Stripe\Customer::retrieve($invoice->customer);
print_r($subscription);
}
Unfortunately I'm not getting any response from the $subscription array. And I have attempted various methods, such as; $subscription = $invoice->plan; or $subscription = $invoice->data->plan; etc...
I do receive data for $invoice & $customer so I know they both function correctly. My main focus is to retrieve the Metadata information:
"metadata": {
"website_ref": "Z8ckRo2x",
"user_id": "1"
}
So I know which account this payment relates to. Hoping somebody might know what I'm doing wrong.
Have you tried $invoice->lines->data->Metadata->website_ref to get the metadata you are after?
Your Invoice consists of a list of subscriptions, in this case just 1. Each subscription is a result of the user selecting a plan. The metadata is stored at the subscription level as it's specific for the customer, not on the plan.