I have the php file
<?php
$str = '{
"champions": [{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125.0,
}
}, {
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550.0,
}
}],
"matches": [{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
}, {"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}]
}';
$array = json_decode($str,true);// read string to array (true means array, false means object)
var_dump($array);
$champions = $array["champions"];
var_dump($champions);
which outputs null for both var_dumps. What is my mistake? Thanks. Is it maybe a problem that there are square brakets in the json snippet?
You have errors in your JSON.
Remove , in the end of [champions][stats] arrays.
please remove comma separation from every last element of champions->stats like below then do decode
{
"champions": [
{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125
}
},
{
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550
}
}
],
"matches": [
{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
},
{
"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}
]
}
Related
I have a wordpress endpoint and I have some json data.
Unfortunately I dont know how to return this json data in the function. I tried json_decode but it doesn't return anything. Then endpoint works. If I use json_encode it returns data, but also include linebreaks and stuff. The problem seems to be with the syntax as it is already a complete json what I have. How can I return something that is already in json syntax?
add_action('wp_ajax_nopriv_inboundCall', 'testFunction');
add_action('wp_ajax_inboundCall', 'testFunction');
function testFunction() {
echo json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}');
die();
}
function testFunction() {
return json_decode('{
"testData": [
{
"_id": "1",
"name": "testName1"
},
{
"_id": "2",
"name": "testName2"
},
],
"testState": {
"1": [
1,
0
"2": [
1,
0
]
}
}'); }
I saved the output of json_decode to a variable and then run json_encode on that variable. Now it seems to work.
function inboundCall() {
$json = json_decode('{
"topics": [
{
"_id": "1",
"name": "davisio",
"crdate": "2022-01-17T12:40:03.430Z",
"modified": "2022-01-17T12:40:03.430Z"
},
{
"_id": "2",
"name": "LoRaWAN",
"crdate": "2022-01-17T12:40:33.848Z",
"modified": "2022-01-17T12:40:33.848Z"
},
{
"_id": "3",
"name": "Kommunale Beziehungen",
"crdate": "2022-01-19T15:17:10.094Z",
"modified": "2022-01-19T15:17:10.094Z"
},
{
"_id": "4",
"name": "Test",
"crdate": "2022-03-31T13:29:41.799Z",
"modified": "2022-03-31T13:29:41.799Z"
}
],
"serviceState": {
"1": [
1,
0,
0,
1,
0,
0,
0,
1
],
"2": [
1,
0,
0,
0,
0,
0,
0,
1
],
"4": [
1,
0,
0,
0,
0,
0,
0,
1
]
}
}');
echo json_encode($json);
die();
}
I am creating a json file from my array:
$file = json_encode($array);
The json file will look like this:
[
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
But I need to create a json file with some little bit different format. The output I need is:
{
"draw": 1,
"recordsTotal": 5000,
"recordsFiltered": 5000,
"data": [
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
}
Is this possible with json_encode?
Create a new array with rest of the info and assign current array data into it as well.
$newArray = array(
'draw'=> 1,
'recordsTotal'=> 5000,
'recordsFiltered'=> 5000,
'data'=>$array
);
$file = json_encode($newArray);
i have the following response, how to sort it depending on the distnace
{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74,
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}
i tried the usort but i didn't make it.
i also tried this answer here but it seems to be different than the one i need
In pure PHP 7
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
As #hdifen suggested, if you're using Laravel it's a breeze to do this.
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "tito",
"distance": 74
},
{
"id": 67,
"name": "liver pool",
"distance": 83
},
{
"id": 67,
"name": "Text",
"distance": 72
}
]
}';
$data = json_decode($json, true);
$data['InnerData'] = collect($data['InnerData'])->sortBy('distance', SORT_REGULAR, true);
$encoded = json_encode($data);
echo $encoded;
Output:
{
"Message":"Done.",
"Status":true,
"InnerData":{
"1":{
"id":67,
"name":"liver pool",
"distance":83
},
"0":{
"id":66,
"name":"tito",
"distance":74
},
"2":{
"id":67,
"name":"Text",
"distance":72
}
}
}
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.5/collections to do sort/filter or do whatever you want to the array.
I am getting a response using Unirest library, i need to separate the data, so that based on that data i can call my next query. Here is full json response i am getting while using Unirest library
echo '<pre>'; print_r($response->raw_body); echo '</pre>';
{
"status": "success",
"images": [
"http://www.example.com/12.jpg"
],
"photos": [
{
"url": "http://www.example.com/12.jpg",
"width": 205,
"tags": [
{
"confidence": 0.978945010372561,
"center": {
"y": 64,
"x": 129
},
"height": 79,
"width": 79,
"tid": "31337",
"attributes": [
{
"smile_rating": 0.56,
"smiling": true,
"confidence": 0.56
}
],
"uids": [
{
"confidence": 0.35399999999999998,
"prediction": "SE2",
"uid": "SE2#SEA1"
},
{
"confidence": 0.28999999999999998,
"prediction": "SE1",
"uid": "SE1#SEA1"
},
{
"confidence": 0.16,
"prediction": "Star1",
"uid": "Star1#SEA1"
},
{
"confidence": 0.106,
"prediction": "SE3",
"uid": "SE3#SEA1"
},
{
"confidence": 0.037999999999999999,
"prediction": "SE6",
"uid": "SE6#SEA1"
},
{
"confidence": 0.035000000000000003,
"prediction": "SE5",
"uid": "SE5#SEA1"
},
{
"confidence": 0.017999999999999999,
"prediction": "SE4",
"uid": "SE4#SEA1"
}
]
}
],
"height": 206
}
]
}
What i am trying is to print like this
Confidence : 0.35399999999999998
Similar: Test2
Well, provided it is a valid JSON string, just use a simple json_decode() with true flag so that it returns an array. Example:
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if($i == 5) break;
echo 'Confidence: ' . $value['confidence'] . '<br/>';
echo 'Similar: ' . $value['prediction'] . '<br/><br/>';
$i++;
}
The release of Unirest 2.0 had many improvements including ability to set custom JSON decode flags
this gives you more control over the response body type parsing method (json_decode)
Disclaimer: I'm the author of unirest-php and I work at Mashape.
The MSW API states:
Our API follows RESTful convention. Querying for information for a location is as simple as calling: http://magicseaweed.com/api/YOURAPIKEY/forecast/?spot_id=10
You’ll receive a JSON array consisting of a series of data representing the forecast for specific timeframes, looking like this:
[
{
"timestamp": 1367366400,
"localTimestamp": 1367366400,
"issueTimestamp": 1367366400,
"fadedRating": 0,
"solidRating": 0,
"swell": {
"minBreakingHeight": 1,
"absMinBreakingHeight": 0.504,
"maxBreakingHeight": 1,
"absMaxBreakingHeight": 0.784,
"unit": "ft",
"components": {
"combined": {
"height": 1.6,
"period": 5,
"direction": 252.47,
"compassDirection": "ENE"
},
"primary": {
"height": 0.5,
"period": 7,
"direction": 92.49,
"compassDirection": "W"
},
"secondary": {
"height": 0.2,
"period": 9,
"direction": 52.9,
"compassDirection": "SW"
},
"tertiary": {
"height": 1.5,
"period": 5,
"direction": 248.62,
"compassDirection": "ENE"
}
}
},
"wind": {
"speed": 6,
"direction": 221,
"compassDirection": "NE",
"chill": 32,
"gusts": 9,
"unit": "mph"
},
"condition": {
"pressure": 1026,
"temperature": 39,
"weather": "10",
"unitPressure": "mb",
"unit": "f"
},
"charts": {
"swell": "htt://chart-1-us.msw.ms/wave/750/1-1367366400-1.gif",
"period": "htt://chart-1-us.msw.ms/wave/750/1-1367366400-2.gif",
"wind": "htt://chart-1-us.msw.ms/gfs/750/1-1367366400-4.gif",
"pressure": "htt://chart-1-us.msw.ms/gfs/750/1-1367366400-3.gif",
"sst": "htt://chart-1-us.msw.ms/sst/750/1-1367366400-10.gif"
}
},
{
"timestamp": 1367377200,
"localTimestamp": 1367377200,
"issueTimestamp": 1367366400,
"fadedRating": 0,
"solidRating": 0,
"swell": {
"minBreakingHeight": 0,
"absMinBreakingHeight": 0.384,
"maxBreakingHeight": 1,
"absMaxBreakingHeight": 0.6,
"unit": "ft",
"components": {
"combined": {
"height": 1.8,
"period": 4,
"direction": 266.06,
"compassDirection": "E"
},
"primary": {
"height": 0.4,
"period": 6,
"direction": 92.53,
"compassDirection": "W"
},
"secondary": {
"height": 0.2,
"period": 9,
"direction": 52.72,
"compassDirection": "SW"
},
"tertiary": {
"height": 1.8,
"period": 4,
"direction": 258.73,
"compassDirection": "ENE"
}
}
},
"wind": {
"speed": 5,
"direction": 255,
"compassDirection": "ENE",
"chill": 34,
"gusts": 7,
"unit": "mph"
},
"condition": {
"pressure": 1025,
"temperature": 41,
"weather": "10",
"unitPressure": "mb",
"unit": "f"
},
"charts": {
"swell": "htt://chart-1-us.msw.ms/wave/750/1-1367377200-1.gif",
"period": "htt://chart-1-us.msw.ms/wave/750/1-1367377200-2.gif",
"wind": "htt://chart-1-us.msw.ms/gfs/750/1-1367377200-4.gif",
"pressure": "htt://chart-1-us.msw.ms/gfs/750/1-1367377200-3.gif",
"sst": "htt://chart-1-us.msw.ms/sst/750/1-1367377200-10.gif"
}
}, THIS CONTINUES ON UNTIL THE END OF THE ARRAY
How do I go about calling on the JSON Array and how can I assign a variable to each item (or access each item to use later in html etc.)?
Thanks.
OK, so if you're using PHP it's easy to access the JSON data, just use the json_decode function so you can access the data as a PHP array and work with it easily.
Your code should follow this tasks:
Load the JSON data from the MagicSeaweed API URL;
Decode the JSON into a PHP array;
Process the PHP array and retrieve the fields you want.
In the following code you just need to replace MYAPIKEY with your real APIKEY, uncomment the line $json = file_get_contents("magicseaweed.com/api/MYAPIKEY/forecast/?spot_id=10"); and comment the other line that's assigning the $json variable with the JSON subset example.
Code:
<?php
// You should fetch the JSON data from the remote location the same
// $json = file_get_contents("magicseaweed.com/api/MYAPIKEY/forecast/?spot_id=10");
// This is just a subset JSON data for this example
$json = '[{"timestamp":1367452800,"localTimestamp":1367452800,"issueTimestamp":1367452800,"fadedRating":0,"solidRating":0,"swell":{"minBreakingHeight":0,"absMinBreakingHeight":0,"maxBreakingHeight":0,"absMaxBreakingHeight":0,"unit":"ft","components":{"combined":{"height":2.5,"period":4,"direction":159.26,"compassDirection":"NNW"},"primary":{"height":1.9,"period":4,"direction":158.68,"compassDirection":"NNW"},"secondary":{"height":1.4,"period":5,"direction":255.73,"compassDirection":"ENE"}}},"wind":{"speed":8,"direction":182,"compassDirection":"N","chill":34,"gusts":13,"unit":"mph"},"condition":{"pressure":1024,"temperature":41,"weather":"10","unitPressure":"mb","unit":"f"},"charts":{"swell":"http:\/\/chart-1-us.msw.ms\/wave\/750\/1-1367452800-1.gif","period":"http:\/\/chart-1-us.msw.ms\/wave\/750\/1-1367452800-2.gif","wind":"http:\/\/chart-1-us.msw.ms\/gfs\/750\/1-1367452800-4.gif","pressure":"http:\/\/chart-1-us.msw.ms\/gfs\/750\/1-1367452800-3.gif","sst":"http:\/\/chart-1-us.msw.ms\/sst\/750\/1-1367452800-10.gif"}}]';
// Decode the JSON data into a PHP array using 'true'
// as 2nd argument of the json_decode function
$data = json_decode($json, true);
// Iterate each of the records and access the data as needed
foreach ($data as $record) {
echo "Timestamp: {$record['timestamp']}\n";
echo "Wind speed: {$record['wind']['speed']}\n";
echo "Temperature: {$record['condition']['temperature']}\n";
}
Output:
Timestamp: 1367452800
Wind speed: 8
Temperature: 41