Reputation: 27
I have a json data file fetched from a cloud like such:
{
"timestamp":1526005337995,
"data":[
{
"_id":"ByWpiEKaM",
"data":"N12E00008",
"raw":[78,49,50,69,48,48,48,48,56],
"timestamp":1525398457512
},
}]}
the file is where sensor data is stored from an Arduino microcontroller and sent to the cloud using a gateway. I'm trying to understand how to convert the data string "N12E00008", where N12 is the project ID, E for Moisture (we also have G for temperature). and the last 2 digit (08) indicating the values extracted from the sensors (8% moisture e.g).
I'm new to JSON and I'm also aware that you can apply the data into a $variable and decode it, however, are what are the procedures to breakdown the "N12E00008" string where the web application can recognise which section of the string is data and information. I am using mySql for database and also in the midst of trying to write a php script to auto decode the values of the data.
Upvotes: 1
Views: 77
Reputation: 23958
I assume the malformed json is a copy paste error.
If not you need to take care of that in the Arduino. You can kind patch the error in PHP but it's better to correct the problem where the problem is.
Then to split the string you have is simple string parsing.
You don't need to use fancy regex functions draining you on memory.
I use substr() and list() just to make it a one liner. The same code could have been on three or more lines, but I figured it's all parsing so why split them apart.
I also use a ternary if to convert the E to moisture.
$arr = json_decode($json, 1);
list($project, $sensor, $percentage) = [substr($arr['data'][0]['data'],0,3), (substr($arr['data'][0]['data'],4,1) == 'E' ? 'Moisture':'Temperature'), substr($arr['data'][0]['data'],-2)];
Now you have three variables, $project
$sensor
$percentage
.
You can see the code in action here:
https://3v4l.org/im38c
Upvotes: 1
Reputation: 800
First, note your json is malformed, and it will not be decoded by php, the correct form is this one:
{
"timestamp":1526005337995,
"data":[
{
"_id":"ByWpiEKaM",
"data":"N12E00008",
"raw":[78,49,50,69,48,48,48,48,56],
"timestamp":1525398457512
}
]
}
decode the json with json_decode into a variable first
$data = json_decode($fetched_data);
then parse your data with some regexp
perg_match('/(?<project_id>^\w{3})(?<type>[EG])(?<value>\d+$)/', $data->data[0]->data, $projectData);
Then, you can access the data inside the $projectData variable as array.
$id = $data['project_id'];
$type = $data['type'];
$value = (int) $data['value'];
I'm using named groups on my regexp, php will index the resulting array with the group names, therefore you can access then on the array by the names implied on the regexp. I use this technique whenever i need to do such simple parsers as that.
Upvotes: 0