Access JSON values in a DRF API - json

How can I access "itemnumber" from this serializer?
Or how can I have a better serializer to access data in order_data[id][lot]['Qty'] format
{
"order_data": {
"id": [
{
"lot": {
"itemnumber": "sint ",
"Qty": 4
}
},
{
"lot": {
"itemnumber": "occa",
"Qty": 2
}
}
],
}
}
dt= AddItemsSerializer(data=request.data)
dt.is_valid(raise_exception=True)
order_data = dt.data.get('order_data')

Try this:
for id_dict in dt.data.get('order_data', {}).get('id', []):
print(id_dict.get('lot', {}).get('itemnumber'))
It will print out all values of itemnumber.

Related

Find the average value in MongoDB from JSON

In my MongoDB (export from JSON file) I have database "dab" with structure like this:
id:"1"
datetime:"2020-05-08 5:09:56"
name:"namea"
lat:55.826738
lon:45.0423412
analysis:"[{"0":0.36965591924860347},{"5":0.10391287134268598},{"10":0.086884394..."
I'm using that db for spark analysis via MongoDB-Spark Connector.
My problem is field "analysis" - I need average result for all values from every interval ("0", "5", "10", ..., "1000"), so I have to sum 0.36965591924860347 + 0.10391287134268598 + 0.086884394 + ... and divide by number of intervals (I have 200 intervals in every column), and finally multiply the result by 100.
My solution would be this one:
db.collection.aggregate([
{
$set: {
analysis: {
$map: {
input: "$analysis",
in: { $objectToArray: "$$this" }
}
}
}
},
{
$set: {
analysis: {
$map: {
input: "$analysis",
in: { $first: "$$this.v" }
}
}
}
},
{ $set: { average: { $multiply: [ { $avg: "$analysis" }, 100 ] } } }
])
Mongo playground
You can use $reduce on that array,sum the values,and then divide with the number of elements and then multiply with 100
db.collection.aggregate([
{
"$addFields": {
"average": {
"$multiply": [
{
"$divide": [
{
"$reduce": {
"input": "$analysis",
"initialValue": 0,
"in": {
"$let": {
"vars": {
"sum": "$$value",
"data": "$$this"
},
"in": {
"$add": [
"$$sum",
{
"$arrayElemAt": [
{
"$arrayElemAt": [
{
"$map": {
"input": {
"$objectToArray": "$$data"
},
"as": "m",
"in": [
"$$m.k",
"$$m.v"
]
}
},
0
]
},
1
]
}
]
}
}
}
}
},
{
"$size": "$analysis"
}
]
},
100
]
}
}
}
])
You can test the code here
But this code has 1 problem, you save data in documents, and MongoDB
doesn't have a function like get(document,$$k), the new MongoDB v5.0 has a $getField but still accepts only constants no variables.
I mean we cant do in your case getField(doc,"5").
So we have the cost of converting each document to an array.

Presto Json Parsing

I have a json field(attached sample) and i need to extract the values in ProvisioningSystem path but it works only if i hardcode the array location.How can i extract the value without hardcoding ?Thanks in Advance!
Code:
TRANSFORM(CAST(JSON_EXTRACT(order_json, '$.Order.Accounts.Account') AS ARRAY), x -> JSON_EXTRACT_SCALAR(x,'$.ProvisioningSystems.ProvisioningSystem[1].SystemName'))
Json:
{
"Order":
{
"Accounts": {
"Account": [
{
"ProvisioningSystems": {},
},
{
"ProvisioningSystems": {
"ProvisioningSystem": [
{
"SystemOrderRef": "12345",
"SystemName": "Testsystem",
"SystemOrderRefType": "Provision"
}
]
},
}
]
},
}
}
}

What's the best way to parse this JSON in dotnet core?

I have a json file similar to this:
[
{
"records": [
{
"originalEventTimestamp": "2020-10-21T17:18:02.5353507Z",
"time": "2020-10-21T17:18:02.5359120Z",
"properties": {
"audit_schema_version": 1,
"event_id": "059B9CA8-29EA-4CC4-AC72-7FAD567C09AD"
}
},
{
"originalEventTimestamp": "2020-10-21T17:18:18.5820720Z",
"time": "2020-10-21T17:18:18.5828543Z",
"properties": {
"audit_schema_version": 1,
"event_id": "00B6B0F4-8CD0-49E2-BE7F-1392BC0C6E05"
}
}
],
"EventProcessedUtcTime": "2020-10-21T17:23:12.7628776Z",
"PartitionId": 1,
"EventEnqueuedUtcTime": "2020-10-21T17:20:35.8420000Z"
}
]
I've been following a JSON tutorial that led me down this path:
JsonDocument document = JsonDocument.Parse(Encoding.UTF8.GetString(eventArgs.Data.Body.ToArray()));
JsonElement root = document.RootElement;
JsonElement recordsElement = root.GetProperty("records");
foreach (JsonElement record in recordsElement.EnumerateArray())
{
Console.WriteLine("\tHello World - number 2a:{0}", record.ToString());
if (record.TryGetProperty("audit_schema_version", out JsonElement audit_schema_version))
{
Console.WriteLine("\tHello World - number 3:{0}", audit_schema_version.ToString());
}
else
{
Console.WriteLine("\tHello World - number 4, no audit_schema_version");
}
}
I'm using System.Text.Json and System.Text.Json.Serialization. How can I parse this and get to the audit_schema_version value?

Parse JSON data with Axios and NodeJS Express (matching a schema for mongoose)

I am trying to parse JSON from an API, and because it has a randomly named property whose value is an object (of which has the data I need), I'm having trouble getting the data from it to match with a schema.
Here is a shortened API response just to show the problem I'm having.
{
"data": {
"1": {
"id": 1,
"name": "First Name",
"quotes": {
"USD": {
"price": 100
}
}
},
"1027": {
"id": 1027,
"name": "Second Name",
"quotes": {
"USD": {
"price": 200
}
}
}
}
}
And a shortened schema:
var coin = new Mongoose.Schema({
id: Number,
name: String,
quotes: {
USD: {
price: Number
}
}
});
So the question is, how would I grab "1"'s object and "1027"'s object without explicitly naming them. And is my schema syntax correct for the objects in question?
Thanks!
You can always use the for...in loop to check whether this data is what you have looking for
const response = {
"data": {
"1": {
"id": 1,
"name": "First Name",
"quotes": {
"USD": {
"price": 100
}
}
},
"1027": {
"id": 1027,
"name": "Second Name",
"quotes": {
"USD": {
"price": 200
}
}
}
}
}
for (let key in response.data) {
if (key === '1') {
console.log('Hey, I find it')
}
console.log(key)
}

Why is the json code wrong?

Why is the json code wrong? I know I can have multi key in XML, but it seem that json doesn't allow.
{
"BackupSettings": {
"Setting":
{
"id": "34345"
},
"Setting": {
"id": "16454"
}
}
}
Indeed, keys within an object are required to be unique in JSON. The canonical way of expressing your data in JSON would be to use an array. It could look something like the following:
{
"BackupSettings": {
"Settings": [
{
"id": "34345"
},
{
"id": "16454"
}
]
}
}
Or even:
{
"BackupSettings": [
{
"id": "34345"
},
{
"id": "16454"
}
]
}