dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.12k stars 4.7k forks source link

[API Proposal]: Support Keys property on JsonObject #84880

Open vllama opened 1 year ago

vllama commented 1 year ago

Background and motivation

Currently to get the Keys of a JsonObject is has to be cast to one of the dictionaries it explicitly implements like (IDictionary<string, JsonNode>)jsonObject).Keys

We are using JsonObject becasue we have to manipulate json quite a bit, and enumerating the keys helps a lot.


### API Proposal

```csharp
namespace System.Text.Json.Nodes;

public partial class JsonObject
{
   public ICollection<string> Keys{get;}
}

API Usage

// Fancy the value
var keys = myJsonObject.Keys;

// Getting the values out
foreach (var key in keys)
    Console.WriteLine(v);
...

Alternative Designs

Extension Method:


public static ICollection<string> Keys(this JsonObject json) {
    return ((IDictionary<string, JsonNode>)json).Keys;
}

### Risks

_No response_
ghost commented 1 year ago

Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.

Issue Details
### Background and motivation Currently to get the Keys of a JsonObject is has to be cast to one of the dictionaries it explicitly implements like `(IDictionary)jsonObject).Keys` We are using JsonObject becasue we have to manipulate json quite a bit, and enumerating the keys helps a lot. ``` ### API Proposal ```csharp namespace System.Text.Json.Nodes; public partial class JsonObject { public ICollection Keys{get;} } ``` ### API Usage ```csharp // Fancy the value var keys = myJsonObject.Keys; // Getting the values out foreach (var key in keys) Console.WriteLine(v); ... ``` ### Alternative Designs Extension Method: ``` public static ICollection Keys(this JsonObject json) { return ((IDictionary)json).Keys; } ### Risks _No response_
Author: vllama
Assignees: -
Labels: `api-suggestion`, `area-System.Text.Json`, `untriaged`
Milestone: -
gregsdennis commented 1 year ago

There are currently the TryGetPropertyValue() and ContainsKey() properties that can help. I've used these extensively in my json-everything libraries.

I'll leave this to the dotnet team to confirm, but I believe there are some optimizations they've implemented (e.g. partial object parsing), and they want to encourage people to use these methods over things like the Keys property (which would require parsing the entire object).

vllama commented 1 year ago

@gregsdennis : thanks for that. I am currently using those as well, but since JsonObject Implements IDictionary, I don't believe enumerating keys would be a performance impact, especially since the use case for enumerating keys is most likely a very flat json structure.