I have the error "Array to string conversion" when I read a JSON

0

I have a problem when I read a JSON from PHP because I do not know how to access a certain level.

When executing the code in PHP :

$json = file_get_contents($url);
$json_data = json_decode($json, true);
$var=$json_data['message']['published-print']['date-parts']['0'];

I get the error:

  

Array to string conversion

The approximate structure of JSON :

{
    "status": "ok",
    "message-type": "work",
    "message-version": "1.0.0",
    "message":{
        "indexed":{"...":"..."},
        "reference-count": 52,
        "publisher": "Elsevier BV",
        "license":["..."],
        "funder":["..."],
        "content-domain":["..."],
        "short-container-title":["..."],
        "cited-count": 0,
        "published-print":{
            "date-parts":[
                2017,
                2,
                "..."
            ]
        }
    },
    "...":"..."
}
    
asked by Yisus 10.03.2017 в 02:19
source

2 answers

0

I will use this JSON as a model:

{
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": "Pedro",
        "lastName": "Sánchez",
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

The ways to access a JSON are many (element by element, by array of elements, within a loop ...), everything depends on the structure of the same and the use you want to give the data.

You can access the elements by level. Example:

  • Access the firstName element within properties:

    $json->properties->firstName;

  • When the element you access is an array as is the case of required, in the example, you access the index:

    $json->required[0]

If the sub-array has many values, you can also read them with an iterator, with a for loop or with a while.

Here are some examples:

DEMO

<?php

$string_json='{
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": "Pedro",
        "lastName": "Sánchez",
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}';

//Crar objeto json
$json=json_decode($string_json);

echo "Acceder por nombres de clave:\n";
echo "Valor de la clave title: ". $json->title;
echo "\nValor de la clave firstName (dentro de properties): ". $json->properties->firstName;
echo "\n\nAlgunas claves pueden tener arrays dentro";
echo "\nValores de required (Array): 1er elemento: ". $json->required[0]. " 2º elemento: ".$json->required[1];


//Iterando
echo "\nAcceder por iterator:\n";
iterator (json_decode($string_json,true));

echo "\nSi no se conoce el contenido y la estructura se puede usar print_r:\n";
print_r ($json);

function iterator ($json)
{
$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($json),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}
}

RESULT

Acceder por nombres de clave:
Valor de la clave title: Person
Valor de la propiedad firstName: Pedro

Algunas claves pueden tener arrays dentro
Valores de required (Array): 1er elemento: firstName 2º elemento: lastName

Acceder por iterator:
title => Person
type => object
properties:
firstName => Pedro
lastName => Sánchez
age:
description => Age in years
type => integer
minimum => 0
required:
0 => firstName
1 => lastName

Si no se conoce el contenido y la estructura se puede usar print_r:
stdClass Object
(
    [title] => Person
    [type] => object
    [properties] => stdClass Object
        (
            [firstName] => Pedro
            [lastName] => Sánchez
            [age] => stdClass Object
                (
                    [description] => Age in years
                    [type] => integer
                    [minimum] => 0
                )

        )

    [required] => Array
        (
            [0] => firstName
            [1] => lastName
        )

)
    
answered by 10.03.2017 в 03:18
0

If your conversion from the JSON to the associative array was successful, you can verify it with

print_r($json_data);

If it was successful then, you are accessing the index as text:

$var=$json_data['message']['published-print']['date-parts']['0'];

should be:

$var=$json_data['message']['published-print']['date-parts'][0];

Or you might be trying to echo an array or object.

    
answered by 29.09.2018 в 16:35