How do I parse a specific json data response? - php

Been yanking my hair out the past few days.
I want to parse just a single piece of data from a string response using Get method.
My php code I'm working with:
<?
include "function.php";
$request_rest->setMethod("GET");
$result = $request_rest->execute();
$response_status = $result[0];
$json_response_data = $result[1];
if ($response_status == "200") {
echo $json_response_data;
} else {
echo $response_status ." - connection failure";
}
?>
The results I get:
{"data1":"value1",
"data2":"value2",
"data3":"value3",
"data4":"value4",
"data5":"value5"}
I only want to display "value3" for my output but instead I'm getting the full string response.

If you know the key of the data you want (the data3 part) you can json_decode the json_response_data:
if ($response_status == "200") {
$decoded = json_decode($json_response_data);
echo $decoded['data3'];
}

Decode the JSON data and access it like any other array:
$data = json_decode($json_response_data, TRUE);
echo $data['data3'];

Related

how to parse json when it give different type of response

I am parsing data from JSON in Android, but JSON response is behaving strangely.
If it contains more than one data the response is like this
{"e":"701",
"data":[{"id":"121"},
{"id":"122"}
]
}
If it contains only one data the response is like this
{"e":"701",
"data":{"1":{"id":"93"}}
}
The code that send JSON response is
$r1=mysql_query($sql1,$con);
$count1=mysql_num_rows($r1);
if($count1>0)
{
while ($row1 = mysql_fetch_assoc($r1)) {
$data1[$i] = $row1 ;
}
}
$c = new Emp();
$c->e = "801";
$c->data =$data1;
echo json_encode($c);
How to parse this in one stretch? Any help would be appreciated.
How about you add this in the while loop ($e will be a variable which in the case above contains 801)
$info = array('e' => $e,
'data' => $data1
);
$rows[] = $info;
and then out of the while loop you take it out with json as an array which will give you the result you need if I get the question right.
echo str_replace("\\","", json_encode($rows));

PHP: Unable to echo values from nested Array in PHP

I want to echo data which is in JSON format. I converted from JSON to PHP array using json_decode() but it is not getting echoed. Blow is my code:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->extract;
?>
I only needed extract data which contains information for that title.
If you run the request in the browser, you will see that the returned JSON does not contain a pageids property, but is of the form
{
"batchcomplete": "",
"query": {
"normalized": [
...
],
"pages": {
...
}
}
}
If all you want is to grap the extract from the first item, you could do:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$page = reset($data->query->pages);
$extract = $page ? $page->extract : null;

how to add extra element to array with array_push in PHP?

I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);

PHP Json Help need?

I need to convert the below result. I generate this JSON array using PHP but now I need the same result into a single curly brace. Below is my PHP code to generate the JSON.
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[] = array(
'code' => array_search($obj['name'], $countries_iso),
'total' => $obj['Total']
);
}
}
header("Content-type: application/json");
#Output the JSON data
print (json_encode($arr));
Output of above PHP code:
[
{
code: "AF",
total: 1
},
{
code: "DZ",
total: 1
},
{
code: "AS",
total: 2
}
]
But I want to show like below result:
{
"AF":1
"DZ": 1,
"AS": 2
}
I guess you want $arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
Your mistake was the fact that you were declaring a new array each time you add something to your original array. This way you assign the correct way :)
Try this code:
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
}
}
header("Content-type: application/json");
#Output the JSON data
//$json = json_encode($arr);
$json = json_encode($arr);
Just do this:
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
But you can get rid of the whole array_search($obj['name'], $countries_iso) if you restrict the query to only return rows WHERE name IN (list of $countries_iso). Look up WHERE and IN for SQL Server.
You need to transform your data structure to an associative array, where the value you are currently storing in code will be the key and the value stored in total will be value.
I'll be able to help better if you post the code that generates your current JSON object

JSON manipulation in PHP?

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?
This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];
$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}
Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

Categories