使用JSONPath编辑JSON
您好SO社区:)!
我想创建一个方法,让用户编辑(或添加)JSON特定的值或对象(由JSONPath定位在JSON中)。 下面简单的例子是我的想法。 用户始终输入要更改的JSON,JSONPath和值/对象。 我正在使用Json.NET库。
方法输入 {json,jsonpath,valuetoedit} || 输出 {new json as string}
示例输入:
{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "JRR Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } }
示例JSONPath:
$.store.book[*].author
要更改的示例值:
NewAuthorSpecifiedByUser
输出 – 新JSON,其中所有作者将更改为“NewAuthorSpecifiedByUser”。
这有可能吗?
第三方软件包json.net允许轻松完成:
-
将JSON解析为
JToken
令牌的LINQ to JSON层次结构。 -
选择JSON值以使用JSONPath语法中的查询字符串通过
SelectTokens
进行修改。 -
使用
JToken.Replace()
将所选值替换为新值。 可以使用JToken.FromObject()
将新值直接序列化为JToken.FromObject()
。
从而:
public static class JsonExtensions { public static JToken ReplacePath(this JToken root, string path, T newValue) { if (root == null || path == null) throw new ArgumentNullException(); foreach (var value in root.SelectTokens(path).ToList()) { if (value == root) root = JToken.FromObject(newValue); else value.Replace(JToken.FromObject(newValue)); } return root; } public static string ReplacePath (string jsonString, string path, T newValue) { return JToken.Parse(jsonString).ReplacePath(path, newValue).ToString(); } }
然后使用它像:
var newJsonAuthorString = JsonExtensions.ReplacePath(jsonString, @"$.store.book[*].author", "NewAuthorSpecifiedByUser");
原型小提琴 。 如果您要允许用户进行一系列编辑,那么将JSON永久保留在JToken
层次结构中可能会更有效,而不是重复地从字符串表示转换为字符串表示。
另请参见如何使用NuGet安装JSON.NET? 。