YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

Feature request: access YAML fields by string rather than full deserialization

Open fj opened this issue 7 years ago • 1 comments

Sometimes one just wants to ask questions about the YAML that's being processed rather than needing to deserialize it into an entire object graph. This is especially common when parts of the structure of the input are user-specified, as in the case of things like Kubernetes cluster definitions.

My ideal API would allow me to use jq-style lookups to enumerate over the YAML and retrieve the pieces of interest. For example, that might look like:

var reader = new FileReader("my-file.yaml");
var listOfAllPodNames = Yaml.Deserialize(reader)
                            .Query(".pods[].name")
                            .As(List<string>);

or

var mapOfPodAttributes = Yaml.Deserialize(reader)
                             .Query(".pods[1].metadata")
                             .As(Dictionary<string, string>);

or

var listOfPodMetadata = Yaml.Deserialize(reader)
                            .Query(".pods[].metadata")
                            .As(Dictionary<string, string>[]);

Given the following YAML:

pods:
-
  name: alpha
  size: 1234
  metadata:
    label-one: four-five-six
-
  name: beta
  size: 3456
  metadata:
    label-two: three-seven-eight
    label-three: four-six-two

then we would expect to see the following results:

// .pods[].name
string[]{"alpha", "beta"}

// .pods[1].metadata
Dictionary<string, string> { {"label-one", "four-five-six"} }

// .pods[].metadata
Dictionary<string, string>[] {
  Dictionary<string, string>{ {"label-one", "four-five-six"} },
  Dictionary<string, string>{
    {"label-two", "three-seven-eight"},
    {"label-three", "four-six-two"}
  }
}

fj avatar Jun 25 '18 23:06 fj

I would also find this feature useful - see referenced issue - it would be very helpful for my use case to also be able to get the character index in the original string of the start of the found element.

gfs avatar Aug 04 '22 22:08 gfs