Whoever designed ( and I dont know why I used the word designed ) this data structure should be taken out and given a basic education…. and then shot.
I dont know of any language where a field or class or property could possibly be expected to allow a space in a name i.e. Measurement 0
and what makes it doubly bad is that json data is supposed to be universally usable in any language.
To the designer: No Cigar not even an old wet stoggy!
However this may at least set you on the right lines to solve your problem.
Its written to run as a PHPCLI script but should work as a webpage as well.
<?php
// create the ridiculous json data you have to use
$j = '{
"Location":{
"name":"rauco",
"Sensor":{
"sensor_type":"oxygen",
"sensor_id":0,
"logger_id":1,
"Measurement 0":{
"timestamp":1406865601,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 1":{
"timestamp":1406865661,
"oxygen":9.9,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 2":{
"timestamp":1406865721,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 3":{
"timestamp":1406865781,
"oxygen":10.4,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 4":{
"timestamp":1406865841,
"oxygen":10,
"temperature":12.5,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 5":{
"timestamp":1406865961,
"oxygen":8.9,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
}
}
}
}';
Now the code
$json = json_decode($j);
$x = 0;
while ( 1 ) {
$impossible_obj_name = "Measurement $x";
if ( isset( $json->Location->Sensor->{$impossible_obj_name}) ) {
echo sprintf( 'timestamp: %s, oxygen %s, temperature: %s, depth: %s, salinity: %s, status: %s'.PHP_EOL,
$json->Location->Sensor->{$impossible_obj_name}->timestamp,
$json->Location->Sensor->{$impossible_obj_name}->oxygen,
$json->Location->Sensor->{$impossible_obj_name}->temperature,
$json->Location->Sensor->{$impossible_obj_name}->depth,
$json->Location->Sensor->{$impossible_obj_name}->salinity,
$json->Location->Sensor->{$impossible_obj_name}->status);
$x++;
} else {
break;
}
}
It should generate this as output, I realise this is probably not what you actually want the end result to be but it demonstrates the syntax you will have to use to get over the disasterous data structure design.
timestamp: 1406865601, oxygen 10.2, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865661, oxygen 9.9, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865721, oxygen 10.2, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865781, oxygen 10.4, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865841, oxygen 10, temperature: 12.5, depth: 5, salinity: 0, status: 1
timestamp: 1406865961, oxygen 8.9, temperature: 12.4, depth: 5, salinity: 0, status: 1
solved how to read Json values [closed]