-1

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?

Thomas Verhoeven
  • 264
  • 2
  • 12

2 Answers2

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.

Eg: Decoding JSON String in Java

0stone0
  • 21,605
  • 3
  • 29
  • 49
-1

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.

Serge
  • 28,094
  • 4
  • 11
  • 35
  • This seems like Javascript? Not JsonPath syntax? – 0stone0 May 17 '22 at 13:01
  • 1
    Thanks for the answer, but I'm not using Javascript. I'm using liquibase changesets in Java Spring to alter json payload after data migrations. This uses the same syntax as JSONPath – Thomas Verhoeven May 17 '22 at 13:30
  • Was just wondering if there was a JsonPath solution without the need to parse the inner json string first – Thomas Verhoeven May 17 '22 at 13:33
  • @ThomasVerhoeven It is impossible , since json path is created to work with java script objects. You can only use a string functions or RegEx for example. – Serge May 17 '22 at 13:36