JSONPath .read() returns an invalid json

150 views Asked by At

I'm writing a function that will filter a JSON using the JSONPath library. I'm running into issues with the object type returned by the .read("$") expression. I want to convert the filtered object back into a JSON however when the Object returned by the read() function is converted into a string using .toString() the JSON is invalid e.g. {id=123} rather than {"id" : "123"} this is causing errors further down the line, if any of the values contain escaped characters the string will throw errors when I try to process it as a JSON.

This article: https://github.com/json-path/JsonPath/issues/217 suggests using jsonString() but this function is part of DocumentContext and the .read() function returns a Linked Hash Map.

I need JSONPath to return a filtered JSON string, how can I achieve this?

Inputs:

Sting json = 
{
   "response_GET":{
      "name":"Luke Skywalker",
      "height":"172",
      "mass":"77",
      "hair_color":"blond",
      "skin_color":"fair",
      "eye_color":"blue",
      "birth_year":"19BBY",
      "gender":"male",
      "homeworld":"https://swapi.dev/api/planets/1/",
      "created":"2014-12-09T13:50:51.644000Z",
      "edited":"2014-12-20T21:17:56.891000Z",
      "url":"https://swapi.dev/api/people/1/"
   }
}


String expression = "$.response_GET";

Function:

try{    
    //Use JsonPath to filter json using the expression parameter then convert the json back into the target page   
    DocumentContext docCon = JsonPath.parse(json);
    Object obj = docCon.read(expression);
    String outputJSON = obj.toString();       

  } catch (Exception ex) {
    String error = "Error in GetPageFromJSONPath: " + ex.getMessage();
    oLog.error(error, ex);
        throw new RuntimeException(error, ex);
    }

outputJSON:

{birth_year=19BBY, created=2014-12-09T13:50:51.644000Z, edited=2014-12-20T21:17:56.891000Z, eye_color=blue, gender=male, hair_color=blond, height=172, homeworld=https://swapi.dev/api/planets/1/, mass=77, name=Luke Skywalker, pxObjClass=ADQURA-FW-Grogu-Int-SWAPI-Root, skin_color=fair, url=https://swapi.dev/api/people/1/}

This invalid JSON doesn't allow me to process the data further.

0

There are 0 answers