Json Flatten 扁平化Json

cs 复制代码
using System;
using System.Linq;
using System.Collections.Generic;
using JsonFlatten; // https://www.nuget.org/packages/JsonFlatten
using Newtonsoft.Json.Linq;

public class Program
{
    private static readonly string json = @"{ 'array': [ 1, 2, 3 ], 'property.with.period.in.path': true, 'number': 123, 'object': { 'a': 'b', 'c': 'd', 'e': 'f' }, 'date': '2014-01-01T23:28:56.782Z', 'string': 'Hello World', 'null': null, 'emptyString': '', 'emptyObject': {}, 'emptyArray': [] }";

    public static void Main()
    {
        JObject jObj = JObject.Parse(json);
        
        // Flatten a JObject to a dictionary. 
        // You can also use: Dictionary<string, object> flattened = new Dictionary<string, object>(jObj.Flatten());
        var flattened = jObj.Flatten();        
        WriteLine("Flattened JObject:\r\n" + ToDebugString(flattened));
        
        // Unflatten a Dictionary<string, object> to a JObject
        JObject unflattened = flattened.Unflatten();
        WriteLine("Unflattened JObject:\r\n" + ToDebugString(unflattened));
        
        WriteLine("JObject is equal to unflattened dictionary: " + JToken.DeepEquals(jObj, unflattened)); // True
        
        // Retrieve and cast an item from the dictionary
        var date = flattened.Get<DateTime>("date");
        WriteLine("\"date\" property: " + date);
        
        // Update an entry
        flattened.Set("date", date.AddDays(5));
        WriteLine("Updated \"date\" property: " + flattened.Get<DateTime>("date")); // 1/6/2014 11:28:56 PM
        
        // Flattened a JObject and remove any JSON properties that have null or empty values e.g. null, "", {}, or []
        var flattenedWithoutEmpty = jObj.Flatten(includeNullAndEmptyValues: false);
        WriteLine("Flattened JObject without empty properties:\r\n" + ToDebugString(flattenedWithoutEmpty));
        WriteLine("Unflattened JObject without empty properties:\r\n" + flattenedWithoutEmpty.Unflatten().ToString());
    }
    
    public static Action<object> WriteLine = (msg) => Console.WriteLine("\r\n" + msg.ToString() + "\r\n");

    public static string ToDebugString<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
    {
        return "{\r\n\t" + string.Join(",\r\n\t", dictionary.Select(kv => kv.Key + " = " + kv.Value).ToArray()) + "\r\n}";
    }
}
相关推荐
星 海6 小时前
【json】cJSON库解析文件
c语言·json·cjson
工具派1 天前
JSON转Excel后18位订单号不对了?数字精度与类型边界实测
json·excel
阿皮 API1 天前
Shopee虾皮商品详情API接口调用实战:Python获取东南亚商品数据与JSON解析
开发语言·python·json
死磕音视频1 天前
让大模型稳定输出 JSON:结构化输出的三种方法与 Python 校验实践
json·大模型api·pydantic·结构化输出
今天的砖头有点烫手啊1 天前
Java 序列化到底怎么选?从 Serializable 到 Protobuf 的演进与选型
java·json
小白学鸿蒙1 天前
OpenHarmony 预置应用配置详解:/system/etc/app/ 下的 5 个 JSON
json·openharmony·预置应用
for_ever_love__1 天前
LangChain 结构化输出:让模型稳定吐出符合 schema 的 JSON
langchain·json
健康活着就好1 天前
# 手写Promise.all和Promise.race,面试再也不怕了
面试·json
Dxy12393102162 天前
MySQL JSON 生成列索引原理、实战与坑点
mysql·adb·json
l1t2 天前
DeepSeek总结的DuckDB 从 JSON 字符串到类型化列
数据库·sql·json