Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual
Related
I send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.
I have an HTML file that I have downloaded using curl and inserted into a string. The HTML file has a lot of content but I am looking to parse a certain section of the document and insert this section into an array. The tricky part of this is that the section that I'm trying to parse is NOT HTML, it's code in JavaScript block:
<!-- script block -->
<script type="text/javascript" src="//external.site.com/76b07.js"></script>
<script>....code.....
"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"},
"235534":{"itemId":"235534","type":"1","image":{"url":"thisotherpic.jpg"}:"summary":"This Other Item"},
</script>
How can I import item information as an array?:
$array = array( "itemId" => "235533", "type" => "0", "image" => "thispic.jpg", "summary" =>"This Item" );
You might use a RegExp to match "....":{....} located between <script> tags. The strings, you're interested in, are JSON variables.
Once you have each json variable in a string, you could try with json_decode()
$json_string = '"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"}';
$json = json_decode($json_string);
$myArray = (array)$json;
Try json_decode function in php
You would first need to figure out how to isolate the data structure using whatever string searching methodologies you can use that are repeatable even when the data changes. It is hard to say what this might be without further context from you about the content around the data structure - i.e. what is the same in all cases, and what varies.
You would then eventually get the data strings and json_decode them as others have suggested.
use regex to match them
preg_match_all('/[0-9]+":{"itemId":"(?P<itemId>[0-9]*)","type":"(?P<type>[0-9]{1})","image":{"url":"(?P<image>.*)"}:"summary":"(?P<summary>.*)}/',$mystring,$elements,PREG_SET_ORDER);
then loop through $elements to get your values
Use explode. For example, something like
$array = explode('","', $string);
that would get close to what you want.
Edit:
This looks like a better fit for you.
I've been using json_encode for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
I have the following code:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
This gives me the following results:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Can anyone tell me why json_encode adds slashes?
update
#Quentin said that something is happening between json_encode and .parseJSON and he's right.
Doing a alert(data.toSource()); gives me the dollowing result:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.
Could it be that the Plupload bind does something to my returned data?
This is my js script:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/" and "\/" are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\".".
This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
Make sure your php script has the right header or it will add the slashes
header('Content-Type: application/json');
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
json_encode will always add slashes.
Check some examples on the manual HERE
This is because if there are some characters which needs to escaped then they will create problem.
To use the json please Parse your json to ensure that the slashes are removed
Well whether or not you remove slashesthe json will be parsed without any problem by eval.
<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>
This is my code and i m able to parse the JSON.
Check your code May be you are missing something while parsing the JSON
I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list.
I have a static list working in this form:
var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];
I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.
Does anyone have any suggestions or solutions? Your help would be greatly appreciated.
Kallum
Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.
Then in your code, after you receive the output from the PHP script, run this:
var mark_list = JSON.parse(responseText);
Based on the output from the PHP script, you may need to do this:
var stuff = JSON.parse(responseText);
var mark_list = [stuff];
This will convert the JSON string the PHP returns into an actual javascript object.
In your PHP code you can do something like this:
$output = array(
array(
'EntId' => 3,
'x' => 100,
'y' => 400,
),
);
echo json_encode($output);
Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.
responseText will indeed just be a text represented by a string, so the way you are outputting it right now won't just do the trick all on its own. There are basically two ways you can do this:
In your javascript, you parse the output the server is giving you. This can be done onn a pure string in whatever way you feel like doing it. For example, you could write javascript to parse the format you gave with curly braces and a colon based syntax. Alternatively, you could use another format (like XML) which will reduce the work a little, but will still leave the interpreting of the output for you to do in the javascript.
You can output to a format used to describe objects and lists. JSON would be the big example of such a format. If you output in JSON, you will get something that resembles the format you used above (JSON stands for Javascript Object Notation and is based on parts of the syntax of javascript) and all you will have to do to be able to use it is to get to the data you want to get to. You can use JSON.parse() for this on most browsers, but an alternative with more widespread support is jQuery's jQuery.parseJSON() (for which you would use jQuery, which you should also provide in that case)
I am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify