Json_Decode to Array

json_decode to array

As per the documentation, you need to specify true as the second argument if you want an associative array instead of an object from json_decode. This would be the code:

$result = json_decode($jsondata, true);

If you want integer keys instead of whatever the property names are:

$result = array_values(json_decode($jsondata, true));

However, with your current decode you just access it as an object:

print_r($obj->Result);

json_decode to array or to object

This might get closed as opinion based, but for me, I would typically decode to whatever data structure makes the most sense for the use case.

For example, say the JSON described a single item like a book and looked something like this:

{
"title": "Cool Book",
"author": "Amazing Author",
"publisher": "Evil Corporation",
...
}

To me that is an object, in that it is a single item with different properties. I would be likely to want to treat it like an object in my subsequent code, so I would decode it as an object.

Now if the JSON contained the sort of data that may represent a dictionary, map, hash table, etc. sort of structure, where all the key-value pairs were, in essence, similar items, just with different lookups and mapped values, I might consider decoding to an associative array. Maybe a good example of that would be a country code to country name map like this:

{
"AF": "Afghanistan",
"AX": "Aland Islands",
"AL": "Albania",
"DZ": "Algeria",
...
}

I might be inclined to decode this to an associative array, because I don't need any object-oriented representation of this information, since I am just using this for key-value lookups.

To answer your question about other data structures that can be represented in JSON, officially there are only two data structures supported in JSON - objects and numerically-indexed arrays. This is because of the javascript-based roots of the serialization format, where, for example, the concept of an "out-of-the-box" associative array doesn't exist.

You will however find that a number of JSON encoding/decoding libraries across languages do add support for other data structures or types, typically adding handling behavior around primitive data types, but I would not rely on this unless you fully understand the data structures that are going to be passed and how they are going to be encoded/decoded across all applications that might pass the data around.

For example, PHP provides support for certain primitives as shown in this note from the json_encode() documentation:

Note:
Like the reference JSON encoder, json_encode() will generate
JSON that is a simple value (that is, neither an object nor an array)
if given a string, integer, float or boolean as an input value. While
most decoders will accept these values as valid JSON, some may not, as
the specification is ambiguous on this point. To summarise, always
test that your JSON decoder can handle the output you generate from
json_encode().

Finally, with regards to performance, if you get to the point in your application development where the number one concern is optimizing performance for execution time, memory utilization, etc. and you have reason to believe that relatively substantial gains can be made by optimizing the JSON deserialization (and subsequent data access) logic, then you should ultimately test your application with representative data and see what works best for you. My guess is that this would be along the lines of a micro-optimization for most applications.

How to get json decode array value using PHP

json_decode parameter 2 is assoc

When TRUE, returned objects will be converted into associative arrays.

default is false

reference http://php.net/manual/en/function.json-decode.php

json_decode($response, true);

PHP JSON_DECODE ARRAY

Try this:

<?php
$json_contacts ='[{"addr_name":"1","addr_phone":"010-1111-1111"},{"addr_name":"2","addr_phone":"010-1111-1112"},{"addr_name":"3","addr_phone":"010-1111-1113"},{"addr_name":"4","addr_phone":"010-1111-1114"}]';

$contact = json_decode($json_contacts, true);
echo $json_contacts;
echo "\n";
echo '<pre>';
print_r( $contact);

echo '</pre>';
echo "\nTHE END";

Because you echo your previous $json_contacts and you didn't turn on PHP notice. You cannot echo $contact because it's an array.

How to json_decode an json array received from JavaScript?

I am tranfering a note from What does FILTER_SANITIZE_STRING do? but the entire accepted answer in that question explains it a lot better:

First - php_filter_strip. It doesn't do much, just takes the flags you pass to the function and processes them accordingly. It does the well-documented stuff.

Then we construct some kind of map and call php_filter_encode_html. It's more interesting: it converts stuff like ", ', & and chars with their ASCII codes lower than 32 and higher than 127 to HTML entities, so & in your string becomes &. Again, it uses flags for this.

Then we get call to php_strip_tags_ex, which just strips HTML, XML and PHP tags (according to its definition in /ext/standard/string.c) and removes NULL bytes, like the comment says.

(Emphasised the important part).

In short FILTER_SANITIZE_STRING will break your JSON because it will encode things that it should not. If you want to validate this input do not use this filter.

The answer here is to not use FILTER_SANITIZE_STRING.
The sensible way to validate a JSON string is to do json_decode and check if it's null.

$jsonStr = filter_input(\INPUT_GET, 'myparam'); 
var_dump($jsonStr);
var_dump(json_decode($jsonStr, true));

json_decode returns json string not an array

It looks like @tkausl is correct. The JSON you're receiving has been double-encoded. Since it's double-encoded, a temporary solution would be to double-decode it.

$data = json_decode(json_decode($json), true);

But the real solution is to figure out why it's like that to begin with and fix it (if it's yours to fix).

Getting an array result from json_decode

Set the second parameter of json_decode to true to force associative arrays:

$decode = json_decode($dbresult, true);

How to extract and access data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

  • scalars: strings, ints, floats, and bools
  • nulls (a special type of its own)
  • compound types: objects and arrays.

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
"type": "donut",
"name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
echo $topping, "\n";
}

Glazed

Chocolate with Sprinkles

Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
"foo": "foo value",
"bar": "bar value",
"baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'

The value of key 'bar' is 'bar value'

The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)

[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)

[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)

)

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
"type": "donut",
"name": "Cake",
"toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:

  • Processing large JSON files in PHP
  • How to properly iterate through a big json file

How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.



Related Topics



Leave a reply



Submit