receive string from a json and convert it to object or array (php - java)

-1

Good morning It's my first post and it's simply because I do not know what else to do: c The issue is that I have a web services where I make a query to a database from php and I get a json of the type String something like this.

[{"id":"1","usuario":"admin","clave":"admin","nombre":"Juan","apellido":"Sepulveda","edad":"25"}][{"id":"2","usuario":"user","clave":"123456","nombre":"Jose","apellido":"Gonzalez","edad":"34"}][{"id":"3","usuario":"rowso","clave":"rowso","nombre":"Juanito","apellido":"Sepulveda","edad":"25"}][{"id":"4","usuario":"nuevo","clave":"123","nombre":"nuevo","apellido":"yourmeh","edad":"58"}][{"id":"5","usuario":"","clave":"","nombre":"","apellido":"","edad":"0"}]

I need to be able to parse those data obtained to be able to use them freely for example.

get user: admin to assign it some variable.

I do not know how to do it if you transfer it to an arrangement and then take it 1 to one or something like that.

Thank you very much

    
asked by Juan Sepulveda 20.11.2017 в 04:47
source

1 answer

0

As a first observation, the string that shows as JSON does not correspond to a string that can be interpreted as an object, it does not have the commas that define each element. You must solve this first. I recommend link to validate the string you want to format.

Having said that, in php the way to convert a json to an array or object is json_decode

Once converted to an iterable data type you can access the data "freely" as you mention it.

A small example where the arrangement is scanned and users are printed:

    $var = '[{"id":"1","usuario":"admin","clave":"admin","nombre":"Juan","apellido":"Sepulveda","edad":"25"},{"id":"2","usuario":"user","clave":"123456","nombre":"Jose","apellido":"Gonzalez","edad":"34"},{"id":"3","usuario":"rowso","clave":"rowso","nombre":"Juanito","apellido":"Sepulveda","edad":"25"},{"id":"4","usuario":"nuevo","clave":"123","nombre":"nuevo","apellido":"yourmeh","edad":"58"},{"id":"5","usuario":"","clave":"","nombre":"","apellido":"","edad":"0"}]
';
$arr = json_decode($var, true);

foreach($arr as $k=> $v)
{
    echo "usuario ".$k.": ".$v['usuario']."<br>";
}

Greetings.

    
answered by 20.11.2017 / 17:49
source