In my php file im using the following,
$obj = ($_POST['data']);
var_dump(json_decode($obj,true));
And i see this result. Is this the correct format? and how do i access the array.
eg, set a new variable $newID the same as row1 id
array(4) {
["row0"]=>
string(92) "{"id":"157","name":"123","basic":"123123123","submitter":"Keith","status":"review"}"
["row1"]=>
string(169) "{"id":"158","name":"TEST RESOURCE","basic":"Please state the type of work.","submitter":"Keith","status":"review"}"
["row2"]=>
string(107) "{"id":"159","name":"TEST OTHER","basic":"testing for other","submitter":"Keith","status":"review"}"
["row3"]=>
string(160) "{"id":"160","name":"Name","basic":"type of work","submitter":"Keith","status":"review"}"
}
heres whats in POST in firebug
data {"row0":"{\"id\":\"157\",\"name\":\"123\",\"basic\":\"123123123\",\"submitter\":\"Keith\",\"status\":\"review\"}","row1":"{\"id\":\"158\",\"name\":\"TEST RESOURCE\",\"basic\":\"Please state the type of work.\",\"submitter\":\"Keith\",\"status\":\"review\"}","row2":"{\"id\":\"159\",\"name\":\"TEST OTHER\",\"basic\":\"testing for other\",\"submitter\":\"Keith\",\"status\":\"review\"}","row3":"{\"id\":\"160\",\"name\":\"Name\",\"basic\":\"type of work\",\"submitter\":\"Keith\",\"status\":\"review\"}"}
Each "row" of the array is another JSON string. It seems like the data was double-encoded, like:
$array = json_encode(
array(
'row0' => json_encode(array('id' => '157', ...)),
...
)
)
This is incorrectly encoded data, unless you wanted JSON objects inside JSON objects. To work with it, you need to json_decode each individual item again. Better though: fix the encoding step.
Related
I have a json file:
$json='[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
and my forms post data in variable
vars="fname"=>"Ameur","lname"=>"KHIL"
"fname"=>"Marak","lname"=>"Cristo"
and I like to insert in between my json content with variable to get the final json like this:
$result='[{"Email":"myemail1#domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2#domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.
Parsing the JSON-String
$json = json_decode('[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
Adding the new vars value and removing the additional ones. This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
And getting your result in a JSON-String
$result = json_encode($json);
I will explain below exactly what is happening. Any thoughts on a fix would be great thanks.
See below my PHP array..
$myArray = array( 145 => true, 134 => true, 152 => true);
My array then var dumped..
array(3) { [145]=> bool(true), [134]=> bool(true), [152]=> bool(true) }
I then json encode my array..
$myJson = json_encode($myArray);
My encoded json var dumped result is..
string(34) "{"145":true,"134":true,"152":true}"
I then set my cookie using the json string like this..
setcookie('mycookie', $myJson);
Then this is the cookie contents after it has been set..
%7B%22145%22%3Atrue%2C%22134%22%3Atrue%2C%22152%22%3Atrue%7D
OK this where the trouble begins
I then get the cookie contents using this..
$myCookie = $_COOKIE['mycookie'];
This a var dump of $myCookie..
string(40) "{\"131\":true,\"134\":true,\"152\":true}"
As you can see this not the same string that I set in the cookie. There are now backslashes like its being escaped or something. Why is this happing?
If I try and decode the json now it returns NULL.
Can anyone understand why this is happening? Surely I shouldn't have to string replace these back slashes? All I want to do decode the json. My original encoded string decodes fine, its just when it's added to the cookie, it corrupts my json.
I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php
I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")
I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);