0

This question sounds like it has already been asked on SO, but I ask it anyway because the existing answers did not work for me and I'm not sure how better to phrase it, as I am new to R and don't entirely grasp the intricacies of its data types.

Time for a minimal example. I am looking for a transformation of target such that targetObject is exactly equal to referenceObject.

reference = '{"airport":[{"name":"brussels","loc":{"lat":"1","lon":"2"}}],"parking":[{"name":"P1"}]}'
target =    '{"airport":{"name":"brussels","loc":{"lat":"1","lon":"2"}},"parking":{"name":"P1"}}'

referenceObject = jsonlite::fromJSON(reference)$airport
x =               jsonlite::fromJSON(target)$airport

# Transformation
targetObject = do.call(rbind.data.frame, x)

# Currently prints FALSE, should become TRUE
results_same = identical(referenceObject, targetObject)
print(results_same)

I would expect this to be very simple in any language, but R seems to handle the nested loc lists very differently depending on the shape of the outer object airport.

Jodiug
  • 5,425
  • 6
  • 32
  • 48
  • Look at the `str` of both objects (*referenceObject* and *targetObject*) to see their differences. – Parfait Sep 01 '19 at 00:58
  • I know this isn't that helpful, but you can delete all of the useless brackets with some regex like [this](https://stackoverflow.com/questions/7195805/remove-square-brackets-from-a-string-vector) – InfiniteFlash Sep 01 '19 at 04:38
  • 1
    Bonus points? Do you perhaps see how we might find that insulting? – IRTFM Sep 01 '19 at 06:50
  • @42- Figure of speech, I don't know why it bothers you so much but I will rephrase. – Jodiug Sep 02 '19 at 01:12

1 Answers1

1

I managed to find a solution by serializing back to JSON. It's not elegant but at least it works.

# Transformation
targetObject = jsonlite::fromJSON(jsonlite::toJSON(list(x), auto_unbox = TRUE))

For now I will not mark this answer as correct because it's more of a workaround than an ideomatic solution.

Jodiug
  • 5,425
  • 6
  • 32
  • 48
  • Why do you think a one-line solution using a JSON parser to parse JSON is inelegant? Seems like data was incorrectly imported, so you go back and import it correctly. – Gregor Thomas Sep 03 '19 at 15:20
  • @Gregor I think it's inelegant because the data was already deserialized. Now the flow is (1) deserialization (2) serialization (3) deserialization. I think it should be possible to achieve the same transformation with R functions operating on R data structures, without resorting to string-based tactics. – Jodiug Sep 03 '19 at 15:33
  • @Gregor I agree, I am trying to remove the band-aid. Flatten does not work, I think that might be because `target` itself is not a list. How would you use flatten here to get the desired output? https://rextester.com/NEI58996 – Jodiug Sep 04 '19 at 13:33
  • Oops, I was looking at the wrong thing in when I mentioned `flatten`. Deleting the comment. – Gregor Thomas Sep 04 '19 at 13:42