2017-10-11 56 views
1

在C#中可能从char索引位置获取JSONPath吗?即想象在JSON字符串中放置文本游标,并想从该位置知道JSONPath。从字符索引确定JSONPath

JObject o = JObject.Parse(@"{""items"":[{""item1"":""Something1""},{""item2"":""Something2""},{""item3"":""Something3""},{""item4"":""Something4""}]}}"); 

int charindex = 26; 
string jsonpath = o.GetToken(charindex); // imaginary method call 

jsonpath == "$.items[?(@.Item1 == 'Something1')]"; 

我已经搜索了一个库或代码片段来帮助没有运气。什么是最好的方法?正则表达式是否合适?

+0

这不正是你想要的,但'JToken'明确实现['IJsonLineInfo'(https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_IJsonLineInfo.htm)接口。如果[解析](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_Parse_1.htm),则使用['new JsonLoadSettings {LineInfoHandling = LineInfoHandling.Load}'](https:// www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Linq_JsonLoadSettings_LineInfoHandling.htm),那么每个标记都会记住它的行号和字符串中的位置。 – dbc

+0

而且,给定一个'JToken',你可以通过['token.Path'](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Linq_JToken_Path.htm)获得它的路径。 – dbc

回答

2

我认为NewtonSoft的JsonTextReader可以给你想要的,使用Path,LineNumberLinePosition属性。

此代码,例如:

var s = @" 
    { 
     ""obj"": { 
      ""foo"": ""bar"" 
     }, 
     ""arr"": [ 
      1, 
      2, 
      3 
     ] 
    } 
"; 
using(var sr = new System.IO.StringReader(s)) 
{ 
    var r = new Newtonsoft.Json.JsonTextReader(sr); 
    while (r.Read()) 
     Console.WriteLine(r.LineNumber + ":" + r.LinePosition + " : " + r.Path); 
} 

会给下面的输出:

2:5 : 
3:14 : obj 
3:16 : obj 
4:18 : obj.foo 
4:24 : obj.foo 
5:9 : obj 
6:14 : arr 
6:16 : arr 
7:13 : arr[0] 
8:13 : arr[1] 
9:13 : arr[2] 
10:9 : arr 
11:5 : 

但是,如果你真的想只用字符的索引工作,你可能要替换所有换行符和carriage在你的json字符串中返回到空格,所以一切都在一行...

现在要获取字符串中特定位置的路径很简单:

var charIndex = 48; 
var s = @" 
    { 
     ""obj"": { 
      ""foo"": ""bar"" 
     }, 
     ""arr"": [ 
      1, 
      2, 
      3 
     ] 
    } 
"; 
s = s.Replace("\n", " ").Replace("\r", " "); 
var path = ""; 
using(var sr = new System.IO.StringReader(s)) 
{ 
    var r = new Newtonsoft.Json.JsonTextReader(sr); 
    while (r.Read() && r.LinePosition <= charIndex) 
     path = r.Path; 
} 
Console.WriteLine(path); // obj.foo 
+0

梦幻般的答案,谢谢!给我一个正确的方向有用的推动。 – wonea