json-path / JsonPath

Java JsonPath implementation
Apache License 2.0
8.94k stars 1.65k forks source link

Malformed JSON for Non-Array Type #539

Open yvsatyaprasad opened 5 years ago

yvsatyaprasad commented 5 years ago

Hi , Please see the below example JSON { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10 }


When i query store.book using jsonContext.read("$.store.book") i am able to get a well formed JSON But when i query bicycle using jsonContext.read("$.store.bicycle") I am not getting a well formed json, below is the output {color=red, price=19.95}

As you can see the Quotes(") for the name/value pair are gone. This happens only when i am querying a non array type.

hf-kklein commented 5 years ago

Seems like you're using the .toString() method on the read objects. It seems to return a valid JSON for some lists/array but not for dictionaries/objects. This behaviour is rather coincidentally. Use the .jsonString() method on instances of DocumentContext instead or serialise the read objects using the ObjectMapper writeValueAsString() method (in case of Jackson).

yvsatyaprasad commented 5 years ago

Sorry, I am not sure if i understood your recommendation, Below is the code i have , can you please let me know where you want me to do the changes? var jsonFromFile = Source.fromFile("c:\Jway_Example.json").mkString

val jsonContext = JsonPath.parse(jsonFromFile)

// Jway example implementation var Book:Any = jsonContext.read("$.store.book") var cycle:Any = jsonContext.read("$.store.bicycle")

println(Book)
println(cycle)
hf-kklein commented 5 years ago

The variables Book and cycle do have different types. Book is an array, cycle is an object. println(...) doesn't guarantee to print a valid JSON representation. But serializing the read objects as JSON is not part of this library. Please see e.g. this StackOverflow thread: Converting Java objects to JSON with Jackson