Why json_decode doesn't work? - php

can somebody tell me where I'm making the error in the following code? I want to read the title of the 1 Position in the json Array.
<script>
$(document).ready(function(){
$('#loading').click(function(){
var NpPData = [
{
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas"
},
{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
},
{
"title": "High Performance JavaScript",
"author": "Nicholas C. Zakas"
}
];
var NpPDataJSON = JSON.stringify(NpPData);
alert(NpPDataJSON);
$.post("prueba.php", NpPDataJSON, function(r){
$('#result').html('Answer from server: '+r);
},
'json').error(function(e){
alert('FAiled: '+e.statusText);
});
});
});
</script>
And PHP:
$json = $_POST['NpPDataJSON'];
$data = json_decode($json);
echo $data[1]['title'];

Set second parameter to TRUE to have json_decode() to return an array instead of an stdClass object:
$json = $_POST['NpPDataJSON'];
$data = json_decode($json, true); // note the second argument
echo $data[1]['title']; // returns 'JavaScript: The Definitive Guide'
When TRUE, returned objects will be converted into associative arrays.
Also, as per #Stryner's comment, it seems you have misused the $.post() function. You need to set a name to the data you are passing to the server and therefore, pass an object instead of a variable:
$.post("prueba.php", {NpPDataJSON: NpPDataJSON}, function(r){/* ... */}, 'json');

Related

I need to obtain the key string from JSON

I have this JSON in a request for an laravel API:
{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14
}
I need to obtain the string "directLeader" 'cause this key changes in the request and I used that as a reference for a query update.
To convert json to array:
$array = json_decode($json, true);
To get the first key inside associative array:
$firstKey = array_key_first($array['questionary']);
$firstKey will contain your dynamic key.
You need to json_decode() the json you have like so
$json = '{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14
}';
$encoded_json = json_decode($json, true);
dd($encoded_json['questionary']['directLeader']);
Note
the true in json_decode() will convert the object to array, without true it will an object

Zoho - Get json value from returned data

I'm using zoho crm..
I get the json data below returned from a query
however I'm struggling to get the value of a string inside the returned data
Here is a sample of the data returned
"response": {
"result": {
"Deals": {
"row": {
"no": "1",
"FL": [
{
"val": "DEALID",
"content": "3508588000000206039"
},
{
"val": "SMOWNERID",
"content": "3508588000000176021"
},
{
"val": "Amount",
"content": "5000"
}
I'm trying to get the Amount value
Here is the PHP code
$json = file_get_contents($url);
$obj = json_decode($json);
$amount = $obj->result->Deals->row->FL['Amount'];
echo 'Deal Amount : £'.$amount;
Thanks In Advance
You need to change a bit
$amount = $obj->response->result->Deals->row->FL[2]->content;
//--------------^index------------------------^index---^column name need to be correct---
Dealing with Zoho response could get messy. You could use this library to help smoothen things for you.
In the meantime, $obj->response->result->Deals->row->FL[2]->content; should do the trick for you.

Get data from JSON file with PHP (empty result with numbers)

I'm trying to get data from the following JSON file using PHP
I Want To Get All URls (link) ,
http://www.google.com
http://www.bing.com
Json
Here is what I tried
PHP
Thanks
You cannot access an object property using a number, it must be a string.
It is much easier to output json_decode as an array, and access properties that way. To do this, put true as the second parameter.
<?php
$json = '
{
"news": {
"name": "yahoo",
"url": "https://yahoo.com"
},
"links": [
{
"id": "1",
"url": "https://google.com"
},
{
"id": "2",
"url": "https://bing.com"
}
]
}';
$decode = json_decode($json, true);
echo $decode['links'][0]['url'];

Decoding and looping through PHP JSON array

I have the following deocoded JSON array.
I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?
{
"RequestHeader":
{
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context" :
{
"type": "friends,circles"
}
"payload" [ {12345},{12345} ,{2345} ]
}
I tried the following, but it doesn't work
$decoded = json_decode($json_string);
for ($i=0;$i<payload.length;++$i)
{
$id=$decoded->payload[$i];
//do some operation with the id
}
First of all the JSON you provided is invalid. Supposedly the valid one should look like this
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
After you've fixed the problem with JSON provider it will be quite easy to access data
<?php
$json = <<<'JSON'
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
JSON;
$data = json_decode($json, true);
$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
var_dump($id);
}
Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.
When you use json_decode method, the output will be nested arrays
So for example to access context type you need to do the following
echo $decoded["context"]["type"];
And to loop on payload you need to do the following
for ($i=0;$i<$decoded["payload"].length;++$i)
{
$id=$decoded["payload"][$i];
//do some operation with the id
}

Displaying a single array item from JSON in PHP (NODE.JS and EXPRESS API)

I have Express running on a custom node API that breaks down a large JSON into bite sized chunks for mobile usage.
One of the section goes through a mass of items and returns only one of them. However the returned data is still wrapped in [ .. ] which makes working with it tough.
My NODE.JS code snippet that deals with my routed request
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
res.json(with_operatorCode);
});
so if you access the url
http://(domain)3000/ppm/summary/operators/25
the following data is returned
[
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
]
How can I break that object out of the [ .. ] so it is not returned as an array object and only shows as
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
Alternativly, how can I work with the [ .. ] object in PHP? When I am trying to echo it using
$operatorJSON=file_get_contents("operator.json");
$operator=json_decode($operatorJSON);
echo $operator->PPM->text;
It errors if the JSON has the [ ]
I suspect it is being treated as an array object
UPDATE : I tried to flatten the array
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
var obj = arr.reduce(function(x, y, i) {
x[i] = y;
return x;
}, {});
res.json(obj(with_operatorCode));
});
but the object returned is still in [ ]
If i understand correctly , i think the most easy way is use the index to get the element in array
res.json(with_operatorCode[0]);
Of course, the [foo] denotes that it is an array.
You could address the item as [0], but that is more likely to cause an error, if no item exists in the filter:
On the php side:
$operator=json_decode($operatorJSON);
echo $operator[0]->PPM->text;
On the Node side:
res.json(with_operatorCode[0]);
The smarter thing to do would be to handle it as an array:
$operator=json_decode($operatorJSON);
if (is_array($operator) && count($operator))
{
echo $operator[0]->PPM->text;
}
Or, if filter may give you more than one:
$operator=json_decode($operatorJSON);
foreach ($operator as $op)
{
echo $op->PPM->text;
}
Try for this:
function toObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i)
obj[i] = arr[i];
obj rv;
}

Categories