'JSONPath: Get field starting with @ in escaped json string
I want to get a nested field in a json string using JSONPath.
Take for example the following json:
{
"ID": "2ac464eb-352f-4e36-8b9f-950a24bb9586",
"PAYLOAD": "{\"@type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
}
If I want to extract the @type field, I expect to do it like this
$.PAYLOAD.@type
But that doesn't seem to work..
Also tried this:
$.PAYLOAD['@type']
Do I need to use escape chars or something?
Solution 1:[1]
Posting my comment as an answer
"{\"@type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
Isn't JSON, it's a string containing encoded JSON.
Since JsonPath can't decode such string, you'll have to use a language of your desire to decode the string.
Solution 2:[2]
You have to fix the json. PAYLOAD is a string and needs to be parsed. This is a code in javascript but if you are using another language, i am sure you can figure how to parse json from string.
var payload={
"ID": "2ac464eb-352f-4e36-8b9f-950a24bb9586",
"PAYLOAD": "{\"@type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
};
payload.PAYLOAD=JSON.parse(payload.PAYLOAD);
after this you can use a json path
$.PAYLOAD['@type']
or just this
var tp= payload.PAYLOAD['@type'];
UPDATE
You can extract from string using json path and reqular expressions, but it will be just a radicuolus solutions, since json path is created to work with java script objects not with strings. It is much more natural and easier to parse a property at first.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0stone0 |
| Solution 2 |
