MultiLevelJsonExtractor - Extract the desired level - u-sql

I have a JSON document that looks as follows:
{
"Region": "Main",
"MarketLocations": [
{
"MarketName": "Central",
"MarketId": 1,
"SalesCategories": {
"Produce": [
{
"Type": "Apple",
"Name": "Granny Smith",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 24,
"Calories": 45,
"Price": 0.29
}
],
"BakedGoods": [
{
"DateMade": "2016-11-08T14:14:33.712Z",
"Name": "Apple Pie",
"Price": 14.25
}
],
"RestaurantItems": [
{
"Name": "Turkey Sandwich",
"Price": 4.85,
"PreparationTimeInMinutes": 20
}
],
"NonPerishable": [
{
"Name": "Honey Mustard",
"Type": "Condiments"
}
]
}
},
{
"MarketName": "Southern",
"MarketId": 2,
"SalesCategories": {
"Produce": [
{
"Type": "Apple",
"Name": "Granny Smith",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 24,
"Calories": 45,
"Price": 0.29
},
{
"Type": "Plums",
"Name": "Red Plums",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 12,
"Calories": 21,
"Price": 0.33
},
{
"Type": "Pears",
"Name": "Golden Nature",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 20,
"Calories": 40,
"Price": 0.45
}
],
"BakedGoods": [
{
"DateMade": "2016-11-08T14:14:33.712Z",
"Name": "Apple Pie",
"Price": 14.25
}
],
"RestaurantItems": [
{
"Name": "Turkey Sandwich",
"Price": 4.85,
"PreparationTimeInMinutes": 20
}
],
"NonPerishable": [
{
"Name": "Honey Mustard",
"Type": "Condiments"
}
]
}
},
{
"MarketName": "Western",
"MarketId": 3,
"SalesCategories": {
"Produce": [
{
"Type": "Plums",
"Name": "Red Plums",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 12,
"Calories": 21,
"Price": 0.33
},
{
"Type": "Pears",
"Name": "Golden Nature",
"DatePicked": "2016-11-08T14:14:33.712Z",
"ShelfLifeInDays": 20,
"Calories": 40,
"Price": 0.45
}
],
"BakedGoods": [
{
"DateMade": "2016-11-08T14:14:33.712Z",
"Name": "Plum Pie",
"Price": 18.25
}
],
"RestaurantItems": [
{
"Name": "Ham Sandwich",
"Price": 4.85,
"PreparationTimeInMinutes": 20
},
{
"Name": "Chicken Soup",
"Price": 2.25,
"PreparationTimeInMinutes": 5
}
],
"NonPerishable": [
{
"Name": "Mayo",
"Type": "Condiments"
},
{
"Name": "Syrup",
"Type": "Condiments"
},
{
"Name": "Ginger",
"Type": "Spices"
}
]
}
}
]
}
I have the following U-SQL, that processes this JSON file, running inside Visual Studio:
DECLARE #in string=#"/JsonDoc2.json";
DECLARE #out string=#"Output/JsonDoc2.csv";
#produce =
EXTRACT Name string,
DatePicked DateTime,
ShelfLifeInDays int,
Calories int,
Price decimal,
MarketId string,
MarketName string
FROM #in
USING new MultiLevelJsonExtractor("MarketLocations[*].SalesCategories.Produce[*]",
false,
"Name",
"DatePicked",
"ShelfLifeInDays",
"Calories",
"Price",
"MarketId",
"MarketName");
OUTPUT #produce
TO #out
USING Outputters.Csv(outputHeader : true);
This executes without error. The problem is that I am specifically specifying what sales category I want ('produce'). I'd like to change this query so that that all sales categories are included (produce, baked goods etc.) with the category name included. I've not been able to figure out a way to do this.

The JsonType method of the NewtonSoft JsonFunctions class, returns a MAP value which is a key-value pair. You can then reference the key to get the JSON property / object / array names, at least after a few other manipulations with CROSS APPLY and EXPLODE.
For your example, I got the following to work:
REFERENCE ASSEMBLY [Newtonsoft.Json];
REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];
USING Microsoft.Analytics.Samples.Formats.Json;
DECLARE #input string = #"/input/myinputfile.json";
DECLARE #output string = #"output/output.csv";
#json =
EXTRACT Region string,
MarketName string,
SalesCategories string // get the SalesCategories as JSON
FROM #input
USING new MultiLevelJsonExtractor("MarketLocations[*].SalesCategories",
true,
"Region",
"MarketName",
"SalesCategories"
);
// Convert the json string to tuple/MAP
#working =
SELECT Region,
MarketName,
JsonFunctions.JsonTuple(SalesCategories) AS x
FROM #json;
// Explode the tuple as key-value pair;
#working =
SELECT Region,
MarketName,
key,
value
FROM #working
CROSS APPLY
EXPLODE(x) AS y(key, value);
// Explode the value which is JSON
#working =
SELECT Region,
MarketName,
key,
JsonFunctions.JsonTuple(y) AS z
FROM #working
CROSS APPLY
EXPLODE(JsonFunctions.JsonTuple(value).Values) AS x(y);
// Prep the result, naming the items you want
#result =
SELECT Region,
MarketName,
key,
z["Type"] AS Type,
z["Name"] AS Name,
z["DatePicked"] AS DatePicked,
z["ShelfLifeInDays"] AS ShelfLifeInDays,
z["Calories"] AS Calories,
z["Price"] AS Price,
z["DateMade"] AS DateMade,
z["PreparationTimeInMinutes"] AS PreparationTimeInMinutes
FROM #working;
OUTPUT #result
TO #output
USING Outputters.Csv(quoting:false);
My results:
It feels like it could be simplified, but see how you get on. The samples for shredding JSON are in short supply but try here and here.

Related

Getting a specific item in a sub array and selecting one value from it

I want to get the boardgame rank (value) from this nested array in Cosmos DB.
{
"name": "Alpha",
"statistics": {
"numberOfUserRatingVotes": 4155,
"averageRating": 7.26201,
"baysianAverageRating": 6.71377,
"ratingStandardDeviation": 1.18993,
"ratingMedian": 0,
"rankings": [
{
"id": 1,
"name": "boardgame",
"friendlyName": "Board Game Rank",
"type": "subtype",
"value": 746
},
{
"id": 4664,
"name": "wargames",
"friendlyName": "War Game Rank",
"type": "family",
"value": 140
},
{
"id": 5497,
"name": "strategygames",
"friendlyName": "Strategy Game Rank",
"type": "family",
"value": 434
}
],
"numberOfComments": 1067,
"weight": 2.3386,
"numberOfWeightVotes": 127
},
}
So I want:
{
"name": "Alpha",
"rank": 746
}
Using this query:
SELECT g.name, r
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'
I get this (so close!):
{
"name": "Alpha",
"r": {
"id": 1,
"name": "boardgame",
"friendlyName": "Board Game Rank",
"type": "subtype",
"value": 746
}
},
But extending the query to this:
SELECT g.name, r.value as rank
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'
I get this error:
Failed to query item for container Games:
Message: {"errors":[{"severity":"Error","location":{"start":21,"end":26},"code":"SC1001","message":"Syntax error, incorrect syntax near 'value'."}]}
ActivityId: 0a0cb394-2fc3-4a67-b54c-4d02085b6878, Microsoft.Azure.Documents.Common/2.14.0
I don't understand why this doesn't work? I don't understand what the syntax error is. I tried adding square braces but that didn't help. Can some help me understand why I get this error and also how to achieve the output I'm looking for?
This should work,
SELECT g.name, r["value"] as rank
FROM Games g
JOIN r IN g.statistics.rankings
WHERE r.name = 'boardgame'

How to Add data to a nested field in Firebase Firestore using a conditional field path

var k = [
{
"category": "Cars",
"products": [
{
"productName": "Aston Martin",
"quantity": 2,
"costPrice": 13500000,
"coverPhoto": "www.astonmartinphotoUrl.jpg"
},
{
"productName": "Mercedes",
"quantity": 1,
"costPrice": 220000,
"coverPhoto": "www.mercerdezphotoUrl.jpg"
}
]
},
{
"category": "Food",
"products": [
{
"productName": "Pizza",
"quantity": 50,
"costPrice": 30,
"coverPhoto": "www.pizzaphotoUrl.jpg"
},
{
"productName": "Pancake",
"quantity": 3,
"costPrice": 3,
"coverPhoto": "www.pancakephotoUrl.jpg"
}
]
}
];
Given the above code sample, I'm trying to add a new map to the nested list, product using the firebase.arrayUnion()
Map _map =
{
"productName": 'Tesla',
"quantity": 2,
"costPrice": 45000,
"coverPhoto": "www.teslaPhotoUrl.jpg"
};
I want to only add this map only where the key 'category' is equal to 'Cars'
_firebaseFirestoreRef.collection('data').doc(id).update({
"fieldPath to the the list where key category == Cars": FieldValue.arrayUnion([_map])
});
And I want final result to be like this on my firebase firestore database
[
{
"category": "Cars",
"products": [
{
"productName": "Aston Martin",
"quantity": 2,
"costPrice": 13500000,
"coverPhoto": "www.astonmartinphotoUrl.jpg"
},
{
"productName": "Mercedes",
"quantity": 1,
"costPrice": 220000,
"coverPhoto": "www.mercerdezphotoUrl.jpg"
},
{
"productName": 'Tesla',
"quantity": 2,
"costPrice": 45000,
"coverPhoto": "www.teslaPhotoUrl.jpg"
}
]
},
{
"category": "Food",
"products": [
{
"productName": "Pizza",
"quantity": 50,
"costPrice": 30,
"coverPhoto": "www.pizzaphotoUrl.jpg"
},
{
"productName": "Pancake",
"quantity": 3,
"costPrice": 3,
"coverPhoto": "www.pancakephotoUrl.jpg"
}
]
}
];
I know I need to use the FirebaseFirestore FieldPath and some query objects, but I don't know how to use it effectively to achieve this ...
Since your k is an array, you're trying to update an existing element in an array field, which is not possible in Firestore. You'll first need to read the document, get the k array from it, update it in your application code, and then write the resulting field back to the database.
This has been covered quite regularly before, so I recommend looking at some other questions about updating an item in an array.
You can also consider turning the top-level array into a map, using the category for the first-level field name:
products: {
"Cars": [{
"productName": "Aston Martin",
"quantity": 2,
"costPrice": 13500000,
"coverPhoto": "www.astonmartinphotoUrl.jpg"
}, ... ]
"Food": [{
...
}]
}
Now you can add an item to the Cars array with an array union on products.Cars.
As Dharmaraj commented, you could also consider putting the products into a subcollection. This will allow you to query the products separately, and allows you to read the parent document without reading all products.

Cannot access child value on Newtonsoft.Json.Linq.JProperty error

I have this json format I'm making an API using ASP.NET.
{
"0": {
"order_id": 11748,
"complete_date": "2021-04-19 14:48:41",
"shipping_code": "aramex.aramex",
"awbs": [
{
"aramex_id": "1314",
"order_id": "11748",
"awb_number": "46572146154",
"reference_number": "11748",
"date_added": "2021-03-04 03:46:58"
}
],
"payment": {
"method": {
"name": "الدفع عند الاستلام",
"code": "cod"
},
"invoice": [
{
"code": "sub_total",
"value": "120.8700",
"value_string": "120.8700 SAR",
"title": "الاجمالي"
},
{
"code": "shipping",
"value": "0.0000",
"value_string": "0.0000 SAR",
"title": "ارمكس"
},
{
"code": "coupon",
"value": "-13.9000",
"value_string": "-13.9000 SAR",
"title": "قسيمة التخفيض(RMP425)"
},
{
"code": "cashon_delivery_fee",
"value": "5.0000",
"value_string": "5.0000 SAR",
"title": "رسوم الدفع عند الاستلام"
},
{
"code": "tax",
"value": "18.1300",
"value_string": "18.1300 SAR",
"title": " ضريبة القيمة المضافة (15%)"
},
{
"code": "total",
"value": "130.1000",
"value_string": "130.1000 SAR",
"title": "الاجمالي النهائي"
}
]
},
"product": [
{
"id": 69,
"name": "مخلط 4 أو دو بيرفيوم للجنسين - 100 مل",
"sku": "45678643230",
"weight": "0.50000000",
"quantity": 1,
"productDiscount": "",
"images": []
}
]
}
}
How can I reach order_id? I made an object let's say its name is obj1 I tried foreach obj1 and storing into a variable obj1.order_id;
It stored null in the variable. the {"0"} is the numbering of orders starts 0-1-2 etc.
You can deserialize that json to Dictionary<string,dynamic> without creating a new class as following:
var values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
var orderId = values["0"]["order_id"].ToString();
This will give you 11748 as a result.

how can i get the these data array in ui reactnative

i need to display the data in the frontend but
i get my data to lists[] state and console.log(this.state.lists) display below structure in console how can i get the those data in front end
Array [
Object {
"list": Array [
Object {
"id": "123",
"imageUrl": "http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
"name": "Chicken Devill pizza",
"price": 700,
"size": "Medium",
},
],
"uid": "xQ0Kg4PgYwVGFTTPGsXK1WHlJuM2",
},
Object {
"list": Array [
Object {
"id": "1234",
"imageUrl": "http://www.pngmart.com/files/1/Cheese-Pizza.png",
"name": "Cheese pork pizza",
"price": 1500,
"size": "Medium",
},
],
"uid": "xQ0Kg4PgYwVGFTTPGsXK1WHlJuM2",
},
]
it seems data format is wrong, however if you want to extract array info you can do it like this:
let finalArray = [];
for(let i=0;i<response.length;i++){
finalArray .push(response[i].list[0]);
=================
console.log(finalArray )

How to check more then two id at a time

I have been create a catalog service like blow json pattern.
Json pattern :
{
"id": "b01ee924-78d3-4f3a-9568-5ee80cbad7a7",
"VendorName": "string",
"Industy": [
{
"Id": "0350ac6c-ca15-4a1e-9211-ad078fbf443c",
"IdustryId": 0,
"IdustryName": "string",
"Category": [
{
"id": "a7b71770-9daf-4b67-b471-0a8390843544",
"Name": "string",
"Description": "string",
"Subcategory": [
{
"id": "76a6ead4-9f4d-4d6e-9c30-70938f088ea3",
"Name": "string",
"Description": "string",
"Product": [
{
"Id": "abf95277-ccbc-4f9d-aeda-b6cc9c99953b",
"Name": "string",
"CurrentQuantity": 0,
"Tag": "string",
"Unit": "string",
"Price": 0,
"hasMethodOfPreparation": true,
"MethodOfPreparation": [
{
"id": "a78cb9ea-276f-494b-840a-6eab5e7d8f4b",
"Description": "string",
"Price": 0
}
],
"Addons": [
{
"id": "bdf97be3-5dd1-49e9-bdec-7ac0d3288adb",
"Description": "one",
"Price": 0
},
{
"id": "8f03d2e2-be1f-446d-b943-be9b8fe8ec4c",
"Description": "new add",
"Price": 0
I query the data like blow
query:
SELECT product FROM catalog
join industry in catalog.Industy
join category in industry.Category
join product in category.Subcategory.Product
where catalog.id ='" + itemId + "'
actual result:For a specific vendor ,industry ,category,sub category i need to get and create product.
note: here more than one indutry,category,sub category .
{
"Id": "abf95277-ccbc-4f9d-aeda-b6cc9c99953b",
"Name": "string",
"CurrentQuantity": 0,
"Tag": "string",
"Unit": "string",
"Price": 0,
"hasMethodOfPreparation": true,
"MethodOfPreparation": [
{
"id": "a78cb9ea-276f-494b-840a-6eab5e7d8f4b",
"Description": "string",
"Price": 0
}
but i need to check the industry id ,category id and sub category id.
How to do that,
Please give me suggestion. thanks in advance .
Please use sql:
SELECT product FROM c
join industry in c.Industy
join category in industry.Category
join Subcategory in category.Subcategory
join product in Subcategory.Product
where industry.Id ='<your item id>'
and category.Id = '<your item id>'
and Subcategory.Id = '<your item id>'
Output:

Resources