strange behavior json_decode - javascript

I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...

First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.

Try using $_POST instead of file_get_contets() which gives you a string.

you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!

Related

having issue to display then data in angularjs via json array

I try to display data in angularjs via json data array but can't figure out or fix the issue when i return the json data from my php file it give me result
["{name:'abc', age:19}","{name:'xyz', age:21}"]
but its not working because in Angular i need data in format something like this
[{name:'abc', age:19},{name:'xyz', age:21}]
now issue is i can't figure out how can i rearrange this array format i tried JSON.parse() but its not working
its my php code
if($xml->product) {
foreach ($xml->product as $node ){
$productName = $node->name;
$productID = $node->productID;
$productPrice = $node->price;
$productURL = $node->imageURL;
$productCat = $node->categories->category;
//$product = "{name: '".$productName."', productid: '".$productID."' }";
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
array_push($data1, $product);
}} else {
echo "error!"; } print json_encode($data1);
problem fixed actually i am passing string in array and then encode with json it give me this double quote issue. now what i fix is change string in array and passed by json it automatically convert these array in object :)
its fixed by changing string into array
$product = "{name: '".$productName."', productid: '".$productID."' }";
replace with this
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");

PHP: How do I can decode a json back into array form in Javascript?

I've an array in my php called as $tempoHeader, for example:
Example Array $tempoHeader
-------
Array
(
[0] => red
[1] => green
[2] => yellow
[3] => blue
)
I want to send it into my external javascript, so I do this one in my php code:
My PHP: header.php
$tempoHeader = array_diff_assoc($modelData, $data);
<script type="text/javascript">var header = <?php echo json_encode($tempoHeader); ?>;</script>
<script type="text/javascript" src="upload_header.js"></script>
In my javascript, I've try to console.log(header); and I got this in my console
Array [ "red", "green", "yellow", "blue" ]
My JS: upload_header.js
$(window).load(function() {
console.log(header); //this work and print out the header json
var myObject = JSON.parse(header);
var myArray = jQuery.parseJSON(header);
console.log(myArray); //didn't print out anything
console.log(myObject); //didn't print out anything
});
How do I can decode this json back as $tempoHeader array form?
Note:
I've read this issue jQuery JSON Decode ( PHP to Javascript), and I've try the suggestion such as jQuery.parseJSON(header);, JSON.parse(header); but I got nothing
$res = json_decode( $tempoHeader, true );
echo $res->array_name[index];
I hope this help
The Problem here is that when you executes your JavaScript, your PHP Script was already executed, to "send a variable back to php" you have to create a new Request.
Mostly it is done via Ajax OR you can add your Array in a hidden input field and "send" it with a form.
So you upload_header.js would look like
$(function () {
$.ajax('update_header.php', {
method: 'POST',
data: {
'header': JSON.stringify(header)
}
})
});
and in your "update_header.php" you would recieve the new header with
$newHeader = json_decode($_POST['header'],true);
hope this helps;)
header already is an array, it is not json / a string and you do not need to parse it.
You send this to javascript:
var header = <?php echo json_encode($tempoHeader); ?>;
So you already have an array in javascript as you have noticed:
Array [ "red", "green", "yellow", "blue" ]
And then you try to parse that as json:
var myObject = JSON.parse(header);
That is not possible nor is it necessary: json is a string and JSON.parse() expects a string as its parameter. You cannot use it on an array.
To use your variable, you can simply use header[0] (red), etc. or loop over it like you do with any other javascript array.

object_to_array and encode - php to js opbject

I send Ajax call to AjaxHandler.php page, the AjaxHandler page call other function in Functions.php (other page).
On success i need to return object from AjaxHandler.php, the object need to have 2 params.
Here is the ajax call:
var month_number = document.getElementById("Month").innerHTML;
var year_number = document.getElementById("Year").innerHTML;
$.get("AjaxHandler.php", { "year": year_number, "month": month_number }, function (encodedata) {
var data = JSON.parse(encodedata);
$("#LinesPlace").html(data);
});
Here is the AjaxHandler.php code the need to handle that:
if(isset($_GET['year'],$_GET['month']))
{
$year = $_GET['year'];
$month = $_GET['month'];
$a = getExpenses($year, $month);
echo $a->pharama;
echo $a->pharamb;
$b = object_to_array($a);
echo $b;
return json_encode($b);
}
Now when i put that url:
http://xxxxxxxxx.com/AjaxHandler.php?year=2015&month=09
Its show me the echo of pharama and pharamb but when i try to convert the object to array and then decode it its just not working, i tryed alot but nothing.
Here is the object_to_array function:
//convert php object to array
function object_to_array($data){
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
*I taked that function from this site from other question..
Please advice =]
Regards,
Rafael.
If you need to decode the JSON as an array or object, json_decode has a parameter specifically for that: http://php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
When TRUE, returned objects will be converted into associative arrays.
For example:
$json_as_object = json_decode($json, false);
$json_as_array = json_decode($json, true);
Attempting to manually convert an object into an array should be unnecessary.
You need to encode it very specifically with JSON_UNESCAPED_UNICODE like this:
$jsonObj = json_encode ( string $json, JSON_UNESCAPED_UNICODE);
I have this code in a standard function for this sort of thing
http://php.net/manual/en/function.json-last-error.php
PS. I think you are over checking it in your object to array function. I would probably choose something like: if(is_array($param)){ .. }
Rafael I cant comment need 50 rep or something:D You say: What you mean unnecessary? you mean i can return the object php as is?
Half of what if am saying: you know the things you put into the function obj_to_array() rigth? That what goes in and it ain't an object so why check it? Who will send it? Do you foresee a $_POST incomming all wrapped up as a nice object and ready to go? Like normally the form does a $_POST / $_GET and provides arrays by default as far as I know? And if you produce an obj elsewhere in your code why put use it as input for this function? Don't you know what you are doing somewhere else in your code? Sure you do and as long as you are concise and precise it will never suddenly be a object returned form $_POST or any function normally outputting arrays or integers etc. Check your output as you created it in the first place? Check your web inputs very well (1 time! and for js injections), then only check your types for validating ambiguous output / inputs of your own like an output that can produce an array or a true / false return value. Checking this output for a value of 1 for a TRUE value of the boolean can result in disappointment because:
if the value of $a is 1 in if($a) do something; then a 1 can be the TRUE value returned as the result of the function that produced the thing that we are checking or the result of count($a). If we then assume the array is length 1 because of a misinterpretation of the value of $a then this can give unintended results? You want to be sure that it is the array in $_array($a) that's doing the talking and not the array for example? Thats all to it I think? Or am I rambling (again)?

Parse json_decode php

I've read a lot of the json_decode questions, tried a variety of different things I can't this to work.
it's the bittrex api
$apikey='4058';
$apisecret='50860';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/public/getticker? apikey='.$apikey.'&nonce='.$nonce.'&market=BTC-LTC';
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$json = json_decode($execResult,true);
I do get an output, now I just want the "Last" value
{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}
I've tried for each
foreach($json->result as $market) {
$lastPrice = $market->Last;
//this was to see if it was an echo problems, tried storing the last price in the db... I get null
$collectionGamerActions->update(array('gamer'=>$gamer),
array('$set'=>array('lastPrice'=>$lastPrice,'reached'=>1)));
//print "last price is $lastPrice";
}
I tried
$lastPrice = $json->result->Last;
and a variety of
$lastPrice = $json[0]['result']['last']
I gave up on php and tried javascript, 1st stringifying he response, then parsing it
var obj = JSON.stringify(response);
var obj =JSON.parse(obj);
console.log("last is " + obj.result.Last + " obj is " + obj);
nothing works... can I get direction in what I'm doing wrong please.
Tried some of the suggestions below
var obj = JSON.stringify(response);
var json = JSON.parse(response);
console.log(json.result.Last);
on the php side the response is generated here
$execResult = curl_exec($ch);
$json = json_decode($execResult);
echo json_decode($json, true);
results in javascript error
SyntaxError: Unexpected number var json = JSON.parse(response);
With the php suggestions
$json = json_decode($execResult);
$json = json_decode($json, true);
var_dump($json['result']['Last']);
results in NULL
As you use (note the second parameter in json_decode):
$json = json_decode($execResult,true);
You will have an associative array, so your value will be in:
$json['result']['last']
Note that $json->result->Last would work if you use json_decode() without the second parameter (the default value, false).
I may be misunderstanding your problem, but... assuming PHP is giving you the string you pasted above, then you can just use JSON.parse (no need for stringify) and grab the result from the resulting object.
var string = '{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
var json = JSON.parse(string);
console.log(json.result.Last); // 0.00002121
Array notation (second argument to json_decode() is true):
$string = '{"success":true,"message":"","result": {"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
$json = json_decode($string, true);
var_dump($json['result']['Last']);
Object notation (second argument to json_decode() is false):
$string = '{"success":true,"message":"","result":{"Bid":0.00002130,"Ask":0.00003341,"Last":0.00002121}}';
$json = json_decode($string);
var_dump($json->result->Last);

How can a JSON model be handled in PHP?

I have a JSON model in my view which I am passing to a PHP script. The model looks like this:
{
FirstName: "Paul",
SurName: "Krampe"
}
I send it to the backend using JSON.stringify(). In PHP, this object arrives as:
{\\\"FirstName\\\":\\\"Paul\\\",\\\"SurName\\\":\\\"Krampe\\\"}
How can I read the members now and assign them to variables?
I tried
$firstName = $newUserObject["FirstName"];
and
$firstName = $newUserObject->FirstName;
but they are both null.
php's function json_decode() decodes string JSON argument into an object and returns that object .
there's also json_encode() function that does the opposite: encodes php object, or array, etc. into JSON string.
Use the built in json_decode function
$array = json_decode($json);
Then access the data with
$array['FirstName'];
Additionnaly you would have to remove the extra slashes in your JSON input by calling before the json_decode function the following format function:
$json = str_replace('\\\\\\', '', $json);
You can do something like this
<?php
$jsonurl = "yourfile.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo $trend->name;
}

Categories