Home > Back-end >  JSONPath: Get field starting with @ in escaped json string
JSONPath: Get field starting with @ in escaped json string

Time:05-18

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?

CodePudding user response:

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.

Eg: Decoding JSON String in Java

CodePudding user response:

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.

  • Related