0

I'm trying to get a Hash from a Json file that has Array Keys, but its return each array key like string.

hash = {[10, 10] => [[1, 1], [5, 5]]}
p JSON.parse(hash.to_json) #=> {"[10, 10]" => [[1, 1], [5, 5]]}

Maybe i should use YAML, any idea?

4
  • 1
    Are your keys arbitrary arrays or are they always arrays of integers? Looks like #to_json is calling [10,10].to_s to stringify the key before encoding it to JSON. I don't think YAML will help. Marshal won't help either, that's not a good serialization format as it depends on the Ruby version. I'd guess that you're going to end up with some custom format (even if it means double encoding by calling [10,10].to_json to stringify the key before JSON encoding the hash, i.e. JSON inside your JSON). Commented Dec 8, 2019 at 9:52
  • 1
    YAML works very well, returning the hash correctly. I really don't figure out how to use this [10,10].to_json, i think it's the same effect and about Marshal i agree with you. Commented Dec 8, 2019 at 10:14
  • Nice, didn't know YAML would do that. You should put that down as an answer and accept it. Commented Dec 8, 2019 at 19:24
  • Well, YAML is not JSON so there is not a correct answer, i think @jörgwmittag answer is the correct but the solution for me was to use YAML. Commented Dec 8, 2019 at 20:44

1 Answer 1

3

There are three slightly different versions JSON, as specified by

While there are small differences between the three, one thing they all agree on: Object Keys are Strings. Always.

In other words, "a Json file that has Array Keys" cannot possibly exist. Whatever you have, it is either a JSON file, but then it cannot have Array Keys, or it is simply not a JSON file.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm just saving a my own hash, because Marshal sometimes it gets corrupted and i could never solve it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.