How to set ignore null fields globally (JsonIgnoreCondition.WhenWritingNull) - json

i need to return an object fro mController in .NET core app 7.0
the object returned with null fields which I don't want to:
{
"field_1": "value",
"field_2": null,
"field_3": null
}
I wish to see
{
"field_1": "value"
}
I found out what i can add an attribute [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] to every filed and it will solve the problem, but i have hundreds of objects and dozens of fields in each of them.
Is it possible to set that property globally?
Somewhere like:
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions... ???
});
I'm not using newstonsoft anymore, please help if you know how to use System.Text.Json.Serialization
Thank you

ok, i removed line:
//builder.Services.AddControllersWithJsonOptions();
and added a new one
builder.Services.AddControllers().AddJsonOptions(j =>
{
j.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
which solved "ignore null properties" problem

Related

Check if a value exists in a json file with python

I've the following json file (banneds.json):
{
"players": [
{
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/07/07aa315f664efa92456569429230bc2c254c3ff8_full.jpg",
"created": 1595050663,
"created_by": "<#128152620136267776>",
"nick": "teste",
"steam64": 76561198046619692
},
{
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/21/21fa5c468597e9c890212b2e3bdb0fac781c040c_full.jpg",
"created": 1595056420,
"created_by": "<#128152620136267776>",
"nick": "ingridão",
"steam64": 76561199058918551
}
]
}
And I want to insert new values if the new value (inserted by user) is not already in the json, however when I try to search if the value is already there I receive a false value, an example of what I'm doing ( not the original code, only an example ):
import json
check = 76561198046619692
with open('banneds.json', 'r') as file:
data = json.load(file)
if check in data:
print(True)
else:
print(False)
I'm always receiving the "False" result, but the value is there, someone can give me a light of what I'm doing wrong please? I tried the entire night to find a solution, but no one works :(
Thanks for the help!
You are checking data as a dictionary object. When checking using if check in data it checks if data object have a key matching the value of the check variable (data.keys() to list all keys).
One easy way would be to use if check in data["players"].__str__() which will convert value to a string and search for the match.
If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values. Another solution would be to make list of "steam64" values for faster and easier checking.
You can use any() to check if value of steam64 key is there.
For example:
import json
def check_value(data, val):
return any(player['steam64']==val for player in data['players'])
with open('banneds.json', 'r') as f_in:
data = json.load(f_in)
print(check_value(data, 76561198046619692))
Prints:
True

Give name to an array of Json in JSON.stringify

In PHP when I want to give a name to an array of json objects I use this line.
$json = json_encode(array("users" => $output));
And this variable would be printed like this.
{"users":[{"user_id":"1"}
But now, I'm building a project in Node.js and I need to give a name to an array, and I don't know how to do it, I'm printing data using this line:
res.send(JSON.stringify(users, null, 4));
[ { "user_id": "1" }, { "user_id": "2" } ]
Thank you.
Just build the object with "root" key users before stringify
res.send( JSON.stringify( { 'users': users } , null, 4) );
You can send json directly specifying data points
res.json({ variablename : thevalue (in your case array)})
if more than one value, just follow the syntax
res.json({ variablename : thevalue1, variablename : value2)})
You can something like this:
{'users': JSON.stringify(users, null, 4)}

Rethinkdb update nested object

I have a document like below-
{
"badgeCount": {
"0e2f8e0c-2a18-499d-8e64-75b5d284e31a": 0 ,
"c0d07f5c-25ff-4829-8145-c33c0871f889": 0
} ,
"createdDate": Mon Oct 10 2016 19:25:10 GMT+00:00 ,
"deleted": false ,
"id": "1330c8b8-38a2-46e4-b93d-f7ff84a423ed",
"joinedUserIds":
[
"0e2f8e0c-2a18-499d-8e64-75b5d284e31a"
]
}
What I want to do is remove joinedUserId "0e2f8e0c-2a18-499d-8e64-75b5d284e31a" and update badgeCount by removing first property "0e2f8e0c-2a18-499d-8e64-75b5d284e31a": 0 in the same query.
I tried updating badgeCount like below-
r.db('mydb').table('discussion').filter({"id": "1330c8b8-38a2-46e4-b93d-f7ff84a423ed"})
.update(function(s){
return {
badgeCount: s('badgeCount').without("0e2f8e0c-2a18-499d-8e64-75b5d284e31a")
}
})
But it does not working. Not sure what I am missing.
Thanks
Anup
Rethink doesn't work like this. It doesn't rewrite object with update.
So, for this case you need to replace current object. And, btw, better to use get instead of filter, cause it's faster. There are doing the same in this situation 'cause id field is unique.
So, if you want to remove "0e2f8e0c-2a18-499d-8e64-75b5d284e31a" from badgeCount, you should use replace:
r.db('mydb').table('discussion').get("1330c8b8-38a2-46e4-b93d-f7ff84a423ed").replace(function(s){
return s.without({badgeCount : {"0e2f8e0c-2a18-499d-8e64-75b5d284e31a" : true}}).without("joinedUserIds").merge({
joinedUserIds : s("joinedUserIds").filter(function(id){
return id.ne("0e2f8e0c-2a18-499d-8e64-75b5d284e31a");
})
});
})

MongoDB - Dynamically update an object in nested array

I have a document like this:
{
Name : val
AnArray : [
{
Time : SomeTime
},
{
Time : AnotherTime
}
...arbitrary more elements
}
I need to update "Time" to a Date type (right now it is string)
I would like to do something psudo like:
foreach record in document.AnArray { record.Time = new Date(record.Time) }
I've read the documentation on $ and "dot" notation as well as a several similar questions here, I tried this code:
db.collection.update({_id:doc._id},{$set : {AnArray.$.Time : new Date(AnArray.$.Time)}});
And hoping that $ would iterate the indexes of the "AnArray" property as I don't know for each record the length of it. But am getting the error:
SyntaxError: missing : after property id (shell):1
How can I perform an update on each member of the arrays nested values with a dynamic value?
There's no direct way to do that, because MongoDB doesn't support an update-expression that references the document. Moreover, the $ operator only applies to the first match, so you'd have to perform this as long as there are still fields where AnArray.Time is of $type string.
You can, however, perform that update client side, in your favorite language or in the mongo console using JavaScript:
db.collection.find({}).forEach(function (doc) {
for(var i in doc.AnArray)
{
doc.AnArray[i].Time = new Date(doc.AnArray[i].Time);
}
db.outcollection.save(doc);
})
Note that this will store the migrated data in a different collection. You can also update the collection in-place by replacing outcollection with collection.

MongoDB: how to select an empty-key subdocument?

Ahoy! I'm having a very funny issue with MongoDB and, possibly more in general, with JSON. Basically, I accidentally created some MongoDB documents whose subdocuments contain an empty key, e.g. (I stripped ObjectIDs to make the code look nicer):
{
"_id" : ObjectId("..."),
"stats" :
{
"violations" : 0,
"cost" : 170,
},
"parameters" :
{
"" : "../instances/comp/comp20.ectt",
"repetition" : 29,
"time" : 600000
},
"batch" : ObjectId("..."),
"system" : "Linux 3.5.0-27-generic",
"host" : "host3",
"date_started" : ISODate("2013-05-14T16:46:46.788Z"),
"date_stopped" : ISODate("2013-05-14T16:56:48.483Z"),
"copy" : false
}
Of course the problem is line:
"" : "../instances/comp/comp20.ectt"
since I cannot get back the value of the field. If I query using:
db.experiments.find({"batch": ObjectId("...")}, { "parameters.": 1 })
what I get is the full content of the parameters subdocument. My guess is that . is probably ignored if followed by an empty selector. From the JSON specification (15.12.*) it looks like empty keys are allowed. Do you have any ideas about how to solve that?
Is that a known behavior? Is there a use for that?
Update I tried to $rename the field, but that won't work, for the same reasons. Keys that end with . are not allowed.
Update filed issue on MongoDB issue tracker.
Thanks,
Tommaso
I have this same problem. You can select your sub-documents with something like this:
db.foo.find({"parameters.":{$exists:true}})
The dot at the end of "parameters" tells Mongo to look for an empty key in that sub-document. This works for me with Mongo 2.4.x.
Empty keys are not well supported by Mongo, I don't think they are officially supported, but you can insert data with them. So you shouldn't be using them and should find the place in your system where these keys are inserted and eliminate it.
I just checked the code and this does not currently seem possible for the reasons you mention. Since it is allowed to create documents with zero length field names I would consider this a bug. You can report it here : https://jira.mongodb.org
By the way, ironically you can query on it :
> db.c.save({a:{"":1}})
> db.c.save({a:{"":2}})
> db.c.find({"a.":1})
{ "_id" : ObjectId("519349da6bd8a34a4985520a"), "a" : { "" : 1 } }