编辑JSON使用JSONPath [英] Editing JSON using JSONPath

查看:2404
本文介绍了编辑JSON使用JSONPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好SO社区:!)

我想创建方法,这将让用户编辑(或增加)JSON特定值或对象(位于JSON由JSONPath )。下面简单的例子是什么在我的脑海。用户总是进入JSON,JSONPath和值/对象改变。我使用Json.NET库。

I want to create method which will let user to edit (or add) JSON specific value or object (located in JSON by JSONPath). Below simple example what is on my mind. User always enters JSON, JSONPath and value/object to change. I'm using Json.NET library.

方法的输入 {JSON,jsonpath,valuetoedit} || 输出 {新的JSON作为字符串}

Method input {json, jsonpath, valuetoedit} || output {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": "J. R. R. 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

Output - new JSON where all authors will be changed to 'NewAuthorSpecifiedByUser'.

是,即使是可能的。

推荐答案

第3方包的 json.net 使得这很容易做到:

The 3rd party package json.net allows this to be done easily:


  1. 解析成JSON一个 LINQ到的层次:// www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm相对=nofollow> JToken 令牌。

  1. Parse the JSON into a LINQ to JSON hierarchy of JToken tokens.

选择JSON值通过 <$ C修改$ C> SelectTokens JSONPath语法使用查询字符串

Select JSON values to modify via SelectTokens using a query string in JSONPath syntax.

使用的 JToken.Replace() 用新值替换选定值。新的值可以直接序列化到一个 JToken 使用的 JToken.FromObject()

Using JToken.Replace() replace the selected values with the new values. A new value can be serialized directly to a JToken using JToken.FromObject().

因此:

public static class JsonExtensions
{
    public static JToken ReplacePath<T>(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<T>(string jsonString, string path, T newValue)
    {
        return JToken.Parse(jsonString).ReplacePath(path, newValue).ToString();
    }    
}



然后用它喜欢的:

Then use it like:

var newJsonAuthorString = JsonExtensions.ReplacePath(jsonString, @"$.store.book[*].author", "NewAuthorSpecifiedByUser");



原型的小提琴。如果你要允许用户做了一系列的修改中,它可能会更有效,让您的JSON在 JToken 层次永久而从和反复转换字符串表示。

Prototype fiddle. If you are going to allow the user to do a series of edits, it will likely be more efficient to keep your JSON in a JToken hierarchy permanently rather that repeatedly converting from and to a string representation.

又见的如何使用的NuGet安装JSON.NET?

这篇关于编辑JSON使用JSONPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆