How do I take a large OpenAPI spec in yaml or json format and flatten it to produce summary, tag, path, httpMethod in C#?
Assume use JObject SelectTokens but I can't figure out the syntax.
string json = File.ReadAllText ("spec.json");
JObject array = JObject.Parse(json);
array.SelectTokens("paths").Dump();
Here's a sample json spec
{
"paths": {
"/entities/{id}": {
"get": {
"summary": "Get Entity",
"tags": [
"Things"
]
},
"put": {
"summary": "Update Entity",
"tags": [
"Things"
]
}
},
"/otherEntities/{id}": {
"get": {
"summary": "Get Other",
"tags": [
"Others"
]
},
"put": {
"summary": "Update Other",
"tags": [
"Others"
]
}
}
}
}
I would want:
"Get Entity", "Things", "/entities/{id}", "get"
"Update Entity", "Things", "/entities/{id}", "put"
"Get Other", "Others", "/otherEntities/{id}", "get"
"Update Other", "Others", "/otherEntities/{id}", "put"
CodePudding user response:
Iterate the
paths
.1.1. Convert
JObject
toDictionary
forpaths
JObject.Iterate as
KeyValuePair
from 1.1.2.1. Get the key as
path
.2.1. Convert the value of the dictionary as
methodKvp
.Iterate as
KeyValuePair
from 2.2.3.1. Get the key as
method
.3.2. Get the
summary
from token "summary".3.3. Get the tag with first value of the array from token "tags".
3.4. Add extracted values to list.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
List<List<string>> result = new ();
foreach (JObject pathObj in array.SelectTokens("paths").AsJEnumerable())
{
Dictionary<string, JObject> pathDict = pathObj.ToObject<Dictionary<string, JObject>>();
foreach (KeyValuePair<string, JObject> pathKvp in pathDict)
{
var path = pathKvp.Key;
var methodDict = pathKvp.Value.ToObject<Dictionary<string, JObject>>();
foreach (KeyValuePair<string, JObject> methodKvp in methodDict)
{
string method = methodKvp.Key;
string summary = (string)methodKvp.Value.SelectToken("summary");
string tag = (string)methodKvp.Value.SelectToken("tags").AsEnumerable().First();
result.Add(new List<string> { summary, tag, path, method });
}
}
}