Parse json_decode php - javascript

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);

Related

How to retrive values from JSON returned by php

Following are my code i want to retrieve values from JSON which is returned by php file.
following are my php code.
$i=1;
foreach($chck as $value){
$qry_a = "SELECT ans_tags FROM wp_pp_actionphp_answers where id=".$value['answer_id'];
$result_a = $wpdb->get_results( $qry_a );
$final[]=array(
"question_id_$i"=>$value['question_id'],
"answer_id_$i"=>$value['answer_id'],
"ans_tags_$i"=>$result_a[0]->ans_tags,
"test_attempt_$i"=>$test_count_by_email,
);
$i++;
}
$jsonstring = json_encode($final);
print_r($jsonstring);//Return JSON to javascript file
exit();
Following are my javascript code.
function get_result(result_id,email){
var data='result_id=' + result_id+"&email="+email;
$.post(
ajaxurl + '?action=actionphp_get_result',
data,
function(result){
document.write(result);
}
);
}
following are my result.
[{"question_id_1":"2","answer_id_1":"3","ans_tags_1":"","test_attempt_1":"181"},{"question_id_2":"1","answer_id_2":"1","ans_tags_2":"This is a tag test","test_attempt_2":"181"}]
How can i retrive values.
You can simply parse the JSON in Javascript:
var data = "{\"a\": 1, \"b\": 2, \"c\": [1,2,3]}"; // your result
var obj = JSON.parse(data);
Then you can simply access the data stored in obj:
obj.a -> 1
obj.b -> 2
obj.c[0] -> 1
EDIT (thanks to Webomatik):
Of course you have to have to pay attention to your result. In your case your result is an array, so you could access the single objects in the array via
obj[0].question_id_1 // "2"
obj[0].answer_id_1 // "3"

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)?

strange behavior json_decode

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..!!

Retrieving and using a json associative array

I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO

Slice a JSON string

I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.

Categories