Need some help with json and jQuery - php

I cannot figure out json for whatever reason, i don't understand why i cannot get this to work.
my json is returning:
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
etc, etc, etc
now i am trying to retrieve it by using:
$.getJSON("lists.php",
{id: aid},function(data){
$.each(data.lists, function(i, info) {
$('.container').append(info.item+info.count);
});
});
but i don't get any data here. can anyone point me in the right direction?
});

You need to return the data like this:
{
"lists":[
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}
In your php, do the following:
echo "{\"lists\":[";
foreach ($lists as $obj) {
echo "{\"item\": \"" . $obj->item . "\", ";
echo "\"count\": \"" . $obj->count . "\"},";
}
echo "]}\n";
Hope that helps!

It looks like you're used to how URL parameters are encoded. JSON works differently.
If you want your object to contain a key lists which contains an array, you should return JSON like this:
{
"lists": [
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}

The above isn't valid JSON. I believe this is the syntax you are looking for, which would be described as "an object with a list property containing an array of items":
{"lists":[{"item":"1","count":"5"},{"item":"1","count":"5"},{"item":"1","count":"5",{"item":"1","count":"5"},{"lists":[{"item":"1","count":"5"}]}
You probably need to adjust your backend code so it's adding a new member to the "lists" array rather than an entirely new "lists" each time.

Related

How can i remove value from object

I am working in the PHP language.
The object is
"[{"value":"test_1"},{"value":"test_2"}]"
and I want
['test_1', 'test_2']
Here is my code...
foreach(json_decode($email) as $emails){
$arr[]=$emails->value;
}
$final = json_encode($arr);
The Output is
"["test_1","test_2"]"
I am not satisfied with this output.
If anyone can help me please give an answer.
assuming that You have the data of array of objects like
$array=[
{
"value":"value1"
},
{
"value":"value2"
}
]
simple use the function pluck() to retrieve data as you want .
$value_array=$array->pluck("value");
Your All keys need to be same to retrieve all values
the $value=["value1","value2"]

echo results from an google safe browsing api array

I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.
var_dump($google_check);
returns the following:
string(488) "{
"matches": [
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
},
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
}
]
}
"
I want to echo results from the array, so something like
echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];
Problem is this returns illegal offset on matches and threat, and only echo's a single character {
What am I doing wrong? How do I echo the results from this array without dumping the entire array?
The response you recieved is in json so you'll need to first json_decode the response.
$decoded = json_decode($google_check, true);
Then you can access it like an array
echo $decoded['matches'][0]['threat'];
echo $decoded['matches'][1]['threat'];
if you want the url value you'll need to do it like this.
echo $decoded['matches'][0]['threat']['url'];
echo $decoded['matches'][1]['threat']['url'];
please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).
Here's a quick explanation on json
https://www.tutorialspoint.com/json/json_php_example.htm

json_decode corrupts my JSON object

I have sent a JSON object to PHP to query my database and return a resultset, however I am getting some unusual behaviour - my JSON object arrives in my script as:
{ "username": "Bobby", "dob": "2015-02-12T00:00:00.000Z" }
Which looks fine too me, in order to perform operations on that data I know I need to use json_decode so that PHP receives it as an array, however when I perform json_decode($request) the output array is:
{ undefined: 24, Bobby: ["dob"]}
I have never had this happen before, and can't quite get my head around exactly why this is happening
EDIT: My complete operation looks like:
if(isset($request)) {
var_dump($request);
$json = json_decode($request, true);
var_dump($json);
}
The first dump is correct, once decoded I get the skewed output
EDIT: I am sending the JSON object from Angular, but I don't think this should cause any problems, however its the only thing I have done differently to what I have in previous apps:
if (!(userName === undefined) && !(userDob === undefined))
{
var json = { "name" : userName, "dob" : userDob };
// Create POST request to the file in the url, send it to PHP in JSON format
var callback = $http.post($scope.url, json );
callback.success(function(data, status) {
...
});
}
EDIT I don't quite understand why, but using print_f or var_dump was delivering skewed results, however if I simply did:
$json = json_decode($request);
$name = $json->name;
$dob = $json->dob;
echo $name;
echo $dob;
It returns the results I would expect.
I believe you may need quotes around the keys:
{ "username": "Bobby", "dob": "2015-02-12T00:00:00.000Z" }
Give that a try.
That's a JavaScript object. Try:
var json = { "name" : userName, "dob" : userDob };
JSON.stringify(json);

json_encode - formatting issue?

I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);

php-mongodb: In PHP, how do I fetch an array stored in monogdb?

Can somebody please tell me where/what I'm doing it wrong and how the conversion should take place? I'm new to PHP and MongoDB so please excuse my naivety...
This is my document in mongo:
{ "_id" : "x", "links" : [1,2,3] }
In PHP, I do this:
foreach($cur as $obj)
echo $obj['_id'] . "-->" . $obj['links']
My output is:
x-->Array
instead of this:
x-->1,2,3
Thanks in advance!
Just to add clarification to the above answer.. what he's doing is really taking an array and casting it into a string with a ',' as a separator.. since the $obj is coming down as an array you would need to cycle through it (unless you're fine displaying it as such).
foreach($obj['links'] as $link){
//do something
}
This way you're keeping it in an array format rather than using an operation to cast it to a string.
Try this:
echo $obj['_id'] . "-->" . implode(',',$obj['links']);

Categories