1

I have a JSON string that contains string keys consisting of only numbers, like this:

{
  "a":"b",
  "1":2,
  "3":"4"
}

When I convert this to an associative array using json_decode, PHP interprets the keys as integers and returns this:

array (
  'a' => 'b',
  1 => 2,
  3 => '4'
)

I can tell json_encode to turn it into an object instead, which results in an object with "string" property names "1" and "3" - but I need to perform some array functions on it so I really need it to be an associative array.

Is there any way at all to achieve this?

The only "solution" I've found is to prepend the JSON keys with something that isn't a digit, like this:

{
  "a":"b",
  "x1":2,
  "x3":"4"
}

But it would be neat if there was a way to tell PHP to keep the keys as strings, since they are in fact quoted as strings in the JSON.

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • 1
    @RussJ Yup, that answers it. I was trying to search for JSON-related questions but didn't really find any clear answers. Looks like the "solutions" are mostly hacks that will bite me in the ass sooner or later, I'll just stick to prepending some text that makes sense in front of my numberstrings. – Magnus Nov 03 '19 at 00:02

0 Answers0