-1

I'm trying to parse a response from an api and pulling my hair out.

Here's a simplified version of the response:

[{"id":123456,"account":6789}]

So I'm basically working with a string that looks like this:

'[{"id":123456,"account":6789}]'

I just need to check that "id" exists, because that means my POST worked fine. But I can't for the life of me figure out how to take that string and get something usable.

How can I get to the value of "id"?

Matt B
  • 89
  • 1
  • 7
  • 1
    [json_decode](https://www.php.net/manual/en/function.json-decode.php) https://3v4l.org/FUW3S – Nick Sep 09 '19 at 23:23
  • @Nick, tried that, json_decode($str)[0]["id] gives me a fatal error: Fatal error: Uncaught Error: Cannot use object of type stdClass as array – Matt B Sep 09 '19 at 23:28
  • `json_decode($string, true)` lol, see how PHP is cool ? – Accountant م Sep 09 '19 at 23:28
  • @MattB take a look at my demo in the comment. I show you how to process that string as either an object or an array. – Nick Sep 09 '19 at 23:29
  • @Nick `json_decode($string, true)` the `true` is what I was missing and it was driving me nuts. Thank you so much! – Matt B Sep 11 '19 at 00:04
  • @MattB no worries - I probably should have made it more clear in my demo that I was changing the second parameter to json_decode. – Nick Sep 11 '19 at 00:08

1 Answers1

0

You can parse your string to an array of JSON objects using json_decode:

json_decode($response_str, true)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55