Displaying empty parameters in JSON - json

I'm building my first API which outputs in JSON, and was wondering: If one of the parameters is empty, is it best to still include that parameter name with an empty value, or not include it at all? For example, if a certain product has batteries it would normally output
"batteries": [
{
"device": "Vehicle",
"number": "4",
"type": "AA",
"included": "Not Included"
},
{
"device": "Remote",
"number": "2",
"type": "AAA",
"included": "Not Included"
}
],
If there are no remote batteries, should I just not include that second section? What if there aren't batteries at all, should I remove the whole battery node?

From the perspective of the json interpreter it won't matter. You should send the JSON however you want the consumer to reconstruct your objects...
Do you want the consumer to have a "Remote" object indicating there are no batteries?
Your example doesn't look like an empty node to me, it looks like meaningful data!
For actually empty nodes it may only matter if you need to keep the serialized object as small as possible (for whatever reason) or if you need to have something else besides JSON look at the serialized object later.
In my personal opinion from an API I like to see all meaningful nodes populated because it gives me an idea of the possibilities of the API.... "Oh, I see, so some of them have remotes and include batteries and this API can tell me that!"

In Javascript, you can treat an absent property in almost the same way you would trean a property set to null:
> a_unset = {}
> a_null = {a: null}
> a_null.a == a_unset.a
true
> a_null.a ? 1 : 0
0
> a_unset.a ? 1 : 0
0
Therefore in JSON, which is based on Javascript and most often consumed by Javascript code, it is customary to omit empty values.
But this is not a hard rule. JSON does provide the null value, so if you think your client code or target users would need to know that a property is there but unset, null might be a good choice. Otherwise just omit it, you will save space.

Related

Expression issues (JSON) with power automate

I'm working on power automate and I have an issue because I've tried a lot expressions and none of them working.
I did a loop (foreach) and inside a message (compose) and there I tried to display "f7626790-0756-43bf-a757-a645a33b853d" from"client"
To do so, I've tried all those expressions:
item()?['client']
item()?['client']?[0]
item()['client']
Here my json file:
[
{
"gift": [
{
"client": "f7626790-0756-43bf-a757-a645a33b853d",
"details": [
{
"client_id": 10859085,
"type": "christmas",
"application_id": "6e6d758d-8e74-3ae3-ac84-50eb23ae65f"
}
]
}
]
}
]
Thank's in advance.
Based on the JSON you provided, you have two arrays. So the question for me is, which array do you want to iterate? Both or the inner one?
I'm going to assume both or if not, it won't matter if you only ever have one item for both of them, my answer will still retrieve the client property.
The Initialize Data step has your JSON.
The Initialize Client step is a blank string at this stage.
The For Each Outer Item expression is simply a link to the Data variable as initialized in the first step.
The For Each Gift expression is set as ... item()?['gift'] ... as you can work out, that will loop over each gift item.
Finally, I get the value of the client property using this expression ... item()['client']

Checking for Dict Elements within a List (from json response)

I currently query this API recursively, and for each instance which I send in a request, I want to check inside the returned json for whether there are any objects within the parameter "causes_virtual". If there is an existing entry inside there, such as in this case: "id": 5408600, I want to print('Contains Entry') but if there is nothing within, I want to print('No Entry'). How can I check causes_virtual for whether or not it contains any additional elements within the curly braces? Currently I am using the method of checking for an empty list:
Either: if len(api_response_article[0]['causes_virtual']) == 0: or if not api_response_article[0]['causes_virtual']:
However, neither of these methods seem to do me any good because it seems to only check for items as if it was a traditional list, but from my understanding, it is a dictionary within a list.
{
"additional_info": "",
"approved_at": null,
"approved_by_id": null,
"causes_virtual": [ # THIS SECTION
{
"id": 5408600,
"models": [
"Potatoes"
],
"principals": "Some irrelevant text",
"title": "We farm potatoes or something"
}
],
"created_at": "2021-03-03T01:13:04.477348+00:00",
"created_by_id": 1019500
}
I suppose what I am looking for is the right if statement for seeing if there is anything inside causes_virtual.
Any help or pointers would be greatly appreciated.

How can I get the value from JSON in logic apps

This is my source ( JSON)
{
"Price": {
"For": "840.040",
"From": "2.990"
},
"ArticleNumber": "71151004",
"ArticleNumberPartitionKey": "7115",
"ForStatus": "ACTIVE",
"id": "71151004",
}
My requirement is to get True in Logic apps( Condition) if the JSON file contains "ForStatus":"ACTIVE".
I tried with this command but not working.
json(base64ToString(triggerBody()?['Content']))?['ForStatus']?['ACTIVE']
According to your description, I don't know where your source(json) come from. I'm not sure if the expression json(base64ToString(triggerBody()?['Content'])) you provided can get the json data rather than get null value.
I assume the expression json(base64ToString(triggerBody()?['Content'])) can get the json data. To implement your requirement, you can use json(base64ToString(triggerBody()?['Content']))?['ForStatus'] is equal to ACTIVE, like below screenshot:
If the property ForStatus may not exist in your json data, you can use string(json(base64ToString(triggerBody()?['Content']))) contains "ForStatus":"ACTIVE", like below screenshot:
Please note, use "ForStatus":"ACTIVE"(remove blank space before "ACTIVE") after the "contains" because when you use json() method, it will remove the blank space.

Updating JSON arrays in MarkLogic 9

I'm having trouble working out how to write a bit of XQuery. I have a JSON structure in MarkLogic that looks like:
{
"id": "pres003A10",
"title": "A Course About Something",
"description": "This course teaches people about some things they may not know.",
"author": "A.N. Author",
"updated": "2007-01-19",
"decks": [
{
"id":"really-basic-stuff",
"exclude": ["slide3", "slide12"]
},
{
"id":"cleverer-stuff",
"exclude": []
}
]
}
The exclude array contains the identifiers for slides in decks (presentations are made up of one or more decks of slides). I'm trying to write a piece of code that will look for a slide id in that exclude list and remove it if present or add it if not (a toggle).
I can obtain the array node itself using:
let $exclude := doc('/presentations/presentation.json')/object-node()/decks[id = 'markup-intro']/array-node('exclude')
but I can't for the life of me see how I then update that array to either remove an item or add it. The intention is call a function something like:
local:toggle-slide($presentation) as object-node()
{
(: xdmp:node-update(...) goes here :)
};
So, how do I update that array?
In memory JSON node trees (and XML trees, for that matter) are immutable.
The way to modify a tree is to construct a new tree, copying the nodes that haven't changed and creating the parent node and ancestor node with the changes.
That said, there's an easier way to modify JSON. If you call xdmp:from-json() on the root node, you will get a mutable in-memory map / array structure.
You can then navigate to the array using map:get() on the maps and [ITEM_NUMBER] on the arrays and delete or insert items FOR the appropriate json:array object.
When you're done, call xdmp:to-json() to turn the root map back into a node.
Hoping that helps,
If you need to update the json in the database, you can use xdmp:node-replace. The catch with node-replace is though, that you have to feed it with a named node. To do that, you need to wrap the array-node in an object-node, and then grab the array-node inside the object-node on the fly. Here a working example:
xquery version "1.0-ml";
(: insert test data :)
xdmp:document-insert("/presentations/presentation.json", xdmp:unquote('{
"id": "pres003A10",
"title": "A Course About Something",
"description": "This course teaches people about some things they may not know.",
"author": "A.N. Author",
"updated": "2007-01-19",
"decks": [
{
"id":"markup-intro",
"exclude": ["slide3", "slide12"]
},
{
"id":"cleverer-stuff",
"exclude": []
}
]
}'
))
;
(: node-replace array-node :)
let $exclude := doc('/presentations/presentation.json')/object-node()/decks[id = 'markup-intro']/array-node('exclude')
return xdmp:node-replace($exclude, object-node{
"exclude": array-node{ "other", "slides" }
}/node())
;
(: view if changed :)
doc('/presentations/presentation.json')
Note: consider looking at MarkLogic's Server-side JavaScript (SJS) support. Updating JSON might seem more natural that way, particularly if you need to make multiple changes in one go.
HTH!

Ember-Data: How to get properties from nested JSON

I am getting JSON returned in this format:
{
"status": "success",
"data": {
"debtor": {
"debtor_id": 1301,
"key": value,
"key": value,
"key": value
}
}
}
Somehow, my RESTAdapter needs to provide my debtor model properties from "debtor" section of the JSON.
Currently, I am getting a successful call back from the server, but a console error saying that Ember cannot find a model for "status". I can't find in the Ember Model Guide how to deal with JSON that is nested like this?
So far, I have been able to do a few simple things like extending the RESTSerializer to accept "debtor_id" as the primaryKey, and also remove the pluralization of the GET URL request... but I can't find any clear guide to reach a deeply nested JSON property.
Extending the problem detail for clarity:
I need to somehow alter the default behavior of the Adapter/Serializer, because this JSON convention is being used for many purposes other than my Ember app.
My solution thus far:
With a friend we were able to dissect the "extract API" (thanks #lame_coder for pointing me to it)
we came up with a way to extend the serializer on a case-by-case basis, but not sure if it really an "Ember Approved" solution...
// app/serializers/debtor.js
export default DS.RESTSerializer.extend({
primaryKey: "debtor_id",
extract: function(store, type, payload, id, requestType) {
payload.data.debtor.id = payload.data.debtor.debtor_id;
return payload.data.debtor;
}
});
It seems that even though I was able to change my primaryKey for requesting data, Ember was still trying to use a hard coded ID to identify the correct record (rather than the debtor_id that I had set). So we just overwrote the extract method to force Ember to look for the correct primary key that I wanted.
Again, this works for me currently, but I have yet to see if this change will cause any problems moving forward....
I would still be looking for a different solution that might be more stable/reusable/future-proof/etc, if anyone has any insights?
From description of the problem it looks like that your model definition and JSON structure is not matching. You need to make it exactly same in order to get it mapped correctly by Serializer.
If you decide to change your REST API return statement would be something like, (I am using mock data)
//your Get method on service
public object Get()
{
return new {debtor= new { debtor_id=1301,key1=value1,key2=value2}};
}
The json that ember is expecting needs to look like this:
"debtor": {
"id": 1301,
"key": value,
"key": value,
"key": value
}
It sees the status as a model that it needs to load data for. The next problem is it needs to have "id" in there and not "debtor_id".
If you need to return several objects you would do this:
"debtors": [{
"id": 1301,
"key": value,
"key": value,
"key": value
},{
"id": 1302,
"key": value,
"key": value,
"key": value
}]
Make sense?