gpt4 book ai didi

c# - 将平面 JSON 转换为嵌套 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:40 28 4
gpt4 key购买 nike

我有一个像下面这样的 flat JSON(我不知道怎么调用它,我希望 flat 是正确的词)

{
"id":12947,
"name.first_name":"Honey",
"address.street.number":"23",
"address.city.code":"LL",
"address.street.name":"Narrow Street",
"address.city.name":"Lalaland",
"name.last_name":"Moon",
"books": [
{
"title":"The long story",
"author.first_name":"Brew",
"author.last_name":"Beating",
"type":"novel"
},
{
"title":"Money and morality",
"author.first_name":"Chris",
"author.last_name":"Mas",
"type":"self-help"
}
]
}

请注意,这些字段未按排序顺序排列。

我想将它转换成如下所示的嵌套 JSON:

{
"id":12947,
"name":{
"first_name":"Honey",
"last_name":"Moon"
},
"address":{
"street":{
"number":"23",
"name":"Narrow Street"
},
"city":{
"code":"LL",
"name":"Lalaland"
}
},
"books": [
{
"title":"The long story",
"author": {
"first_name":"Brew",
"last_name":"Beating"
},
"type":"novel"
},
{
"title":"Money and morality",
"author":{
"first_name":"Chris",
"last_name":"Mas"
},
"type":"self-help"
}
]
}

转换它有什么好的算法?

我是 C# 的人,我打算使用 Newtonsoft.Json 将输入的 JSON 解析为 JObject,然后遍历所有字段以检查它们的键并创建嵌套的 JObject。对于数组,我对每个数组项重复相同的过程。

你有什么更好的主意吗?

最佳答案

这是我为感兴趣的人提供的解决方案。

public static string ConvertFlatJson(string input)
{
var token = JToken.Parse(input);

if (token is JObject obj)
{
return ConvertJObject(obj).ToString();
}

if (token is JArray array)
{
return ConvertArray(array).ToString();
}

return input;
}

private static JObject ConvertJObject(JObject input)
{
var enumerable = ((IEnumerable<KeyValuePair<string, JToken>>)input).OrderBy(kvp => kvp.Key);

var result = new JObject();
foreach (var outerField in enumerable)
{
var key = outerField.Key;
var value = outerField.Value;

if (value is JArray array)
{
value = ConvertArray(array);
}

var fieldNames = key.Split('.');
var currentObj = result;

for (var fieldNameIndex = 0; fieldNameIndex < fieldNames.Length; fieldNameIndex++)
{
var fieldName = fieldNames[fieldNameIndex];

if (fieldNameIndex == fieldNames.Length - 1)
{
currentObj[fieldName] = value;
continue;
}

if (currentObj.ContainsKey(fieldName))
{
currentObj = (JObject)currentObj[fieldName];
continue;
}

var newObj = new JObject();
currentObj[fieldName] = newObj;
currentObj = newObj;
}
}

return result;
}

private static JArray ConvertArray(JArray array)
{
var resultArray = new JArray();

foreach (var arrayItem in array)
{
if (!(arrayItem is JObject))
{
resultArray.Add(arrayItem);
continue;
}

var itemObj = (JObject)arrayItem;

resultArray.Add(ConvertJObject(itemObj));
}

return resultArray;
}

关于c# - 将平面 JSON 转换为嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818498/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com