Reputation: 41
Can someone help me with the correct JsonPath syntax to select the 'location' with the name 'US \ East'?
JObject location = new JObject();
location.Add("name", @"US \ East");
JArray locations = new JArray();
locations.Add(location);
JObject properties = new JObject();
properties.Add("locations", locations);
string path = "locations[?(@.name == 'US \\ East')]";
JToken item = properties.SelectToken(path);
The last line throw the following exception:
Newtonsoft.Json.JsonException was unhandled
_HResult=-2146233088
_message=Unknown escape chracter: \
HResult=-2146233088
IsTransient=false
Message=Unknown escape chracter: \
Source=Newtonsoft.Json
StackTrace:
at Newtonsoft.Json.Linq.JsonPath.JPath.ReadQuotedString()
at Newtonsoft.Json.Linq.JsonPath.JPath.ParseValue()
at Newtonsoft.Json.Linq.JsonPath.JPath.ParseExpression()
at Newtonsoft.Json.Linq.JsonPath.JPath.ParseQuery(Char indexerCloseChar)
at Newtonsoft.Json.Linq.JsonPath.JPath.ParseIndexer(Char indexerOpenChar)
at Newtonsoft.Json.Linq.JsonPath.JPath.ParsePath(List`1 filters, Int32 currentPartStartIndex, Boolean query)
at Newtonsoft.Json.Linq.JsonPath.JPath.ParseMain()
at Newtonsoft.Json.Linq.JsonPath.JPath..ctor(String expression)
at Newtonsoft.Json.Linq.JToken.SelectToken(String path, Boolean errorWhenNoMatch)
at Newtonsoft.Json.Linq.JToken.SelectToken(String path)
at JsonPath.Program.Main(String[] args)
Upvotes: 4
Views: 974
Reputation: 43880
It seems that json path is very tricky. Nobody could find any solution for more then 4 years already.
You have to use " @ " for the path string. This way json will get " \ \ " (double backslashes) and translate one as escape character. Without "@" json get only one " \ ", translates it as " \E " and throws an exception
string path = @"locations[?( @.name == 'US \\ East')]";
var item = properties.SelectToken(path);
I can also offer you another way using Linq
var item= properties["locations"]
.Select(a=> ((JObject) a).Properties().FirstOrDefault(b=> (string)b.Value =="US\\East"))
.FirstOrDefault();
the pluses of this approuch are that you can use not only comparing but Contains, StartsWith, EndWith as well.
Upvotes: 2