I want to generate a JSON array with PHP, but it doesn't work well.
My PHP array looks like this:
protected $resultArray = array("1.0" => 0, "1.3" => 0);
then I do this:
return json_encode($resultArray);
but then i've got this:
var array = [{"1.0":2,"1.3":1}];
Why is " replaced with "?
quot; is a quote character (") encoded as HMTL. json_encode() does not produce HTML encoded sequences.
Replace return with echo in return json_encode($resultArray); and you'll see this for yourself.
Most probably the returned string is passed further to a function that runs it through htmlspecialchars() or htmlentities() and this is the correct way to work with it if you put it into an HMTL context.
Use a different viewer class if you need to output only the json_encode()-ed string. I don't know TYPO3 but I guess you should use JsonView; pass it $resultArray as-is and it will call json_encode() for you.
I think you may using etended library for example in wamp server I tested this code and it's work fine
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span
style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));
//output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}
Thanks guys for help!
The solution is (only for typo3). To get a properly correct JSON-Array in the view the JS code has to be improved the following way:
var array = {f:format.htmlentitiesDecode(value:chartarray)};
Related
Good day,
I got a new script (for me it is) that allows you to create a draggable tree view.
The order of the tree structure can be changed and also stored.
I managed to send and fetch the updated structure.
However I have not yet succeeded in unserializing the string.
Before I am going to write my own logic to decode the array I would like to know if PHP knows some functionality by default to solve this issue?
Example
The String that I have :
spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null
The code that generates this string :
serialized[0].hash
I hope anyone could tell me what I have done wrong. OR IF this even a usable structure.
Thanks in advance
Note
The results are bing written by PHP to a file called test.txt
When I try to get the results I try it like this:
<?php
$cont = file_get_contents('test.txt');
$Str = parse_str($cont);
echo '->'.$Str.'<-';
?>
This produces : ><
Hence an empty string.
The following is a working solution:
<?php
$cont = file_get_contents('test.txt');
parse_str($cont, $Str);
echo print_r($Str);
?>
(* the array that comes out of it is pretty useless actually *) but THANKS
This is all you need:
$arr = [];
$string = "spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null";
parse_str($string, $arr);
var_dump($arr);
Source: http://php.net/manual/en/function.parse-str.php
I've just started using JSON to throw around information between pages and I simply can't figure this one out.
Basically, I have one page that's using jquery getJSON to get some JSON data from another page. But the PHP variables won't/can't get replaced with the necessary content.
Here's the jquery script (which is working fine I believe)
$.getJSON("./menu-controller.php", { editId: getEditId, getEditInfo: true },function(data) {
console.log(data);
var id = data.itemId;
alert(id);
});
I can get it to work just fine when using this code on the other page
$json = '{ "itemId":"4" }';
echo $json;
HOWEVER, if I use this, then it won't work
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
So my question is, how can I get $menuId to actually replace itself with the number and come back on the other page correctly?
I've tried messing with the quotes and re-arranging the quotes for 4 hours. It either comes up with an error or it doesn't replace $menuId with the actual number.
You should make a PHP array instead and then convert it to JSON.
For instance:
$array = array();
$array['itemId'] = $menuId;
echo json_encode($array);
Note: there is also a json_decode function that takes in a JSON string and converts it into PHP as well. You might find that useful.
FYI, PHP variables are interpolated in double quotes only and not in single quotes. So, you've to do something like this:
$json = "{ \"itemId\":$menuId }";
echo $json;
Please see the demonstration over here: http://codepad.viper-7.com/CDC0oM
In this sample:
$menuId = 4;
$json = '{ "itemId":$menuId }';
echo $json;
You have wrapped your JSON string in single quotes. PHP substitutes values in double quotes, so the value is not substituted here, and the vale you echo is
{ "itemId":$menuid } - this is not valid JSON.
You're better off creating a PHP array and using json_encode() to create the SON string:
echo json_encode(array("itemId"=>$menuId));
The problem is that you've enclosed your PHP variable within single (rather than double) quotes, so PHP isn't looking in the string for variables to replace.
So this should work:
$json = "{ \"itemId\": $menuId}";
As well as the json_encode method suggested by Cezary Wojcik (which is going to be a lot more flexible if the data gets more complex!).
I have tried lots of different ways, and using many diffent PHP and JS functions to try to achieve this.
Hoe to i turn this json object ;
"lines" : ["text line 1<br/>","text line 2<br/>","text line 3<br/>","text line 4<br/>"]
Into this string, so that i can add to a HTMl div
text line 1<br/> text line 2<br/> text line 3<br/> text line 4<br/>
No, quotes, brackets or anything else.
In it's simplest form all i have is stringify;
lines = JSON.stringify(obj.lines)
but the above outputs, brackets, quotes, and commas
Sorry if this is a simple and silly question, but i h (finishing now (embarrassed!)) ave searched everywhere for a simple answers. Nothing stands out.
Check out Array.join:
var html = obj.lines.join("");
Example: http://jsfiddle.net/VXbs7/
You have a JSON string. You need to parse it into a data structure, then get the array of strings, and loop over them (outputting as you go).
If you're doing this from javascript, it's quite easy. JSON is native to javascript and can be interpreted as an object quite simply. It looks like you only have half your JSON object pasted in your question though. A whole JSON object is wrapped in [] or {} (unless it's just a string or number type, but then it's not an object).
Anyway, if you're in PHP - you can easily json_decode() this string and loop it like so:
<?php
$arr = json_decode($json_string, true); //true makes it an array instead of object
foreach ($arr['lines'] as $line)
{
echo $line;
}
If you're trying to accomplish it in javascript (in the browser), it's also quite easy (assuming your string is stored in a php variable, and that you're using jquery for dom manipulation)
<script type="text/javascript">
var obj = <?= $json_string; ?>,
mydiv = $('#mydiv);
for (key in obj['lines'])
{
var line = obj['lines'][key];
mydiv.append(line);
}
</script>
both of those should give you the output you're looking for
I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";
I am parsing a json string like so:
ring = JSON.parse(response);
Now, ring is an object but ring.stones is just a string when it should be an object as well.
If I call:
ring.stones = JSON.parse(ring.stones);
It is now the correct object.
I didn't know if this is correct behavior or if maybe I have an issue somewhere stopping it from parsing recursively? If it is supposed to parse recursively, are there any known issues that would prevent it?
Update
Here is the full response before parsing:
{"ring_id":"9","stone_count":"4","style_number":"style 4","syn10":"436.15","gen10":"489.39","syn14":"627.60","gen14":"680.85","available":"yes","type":"ring","engravings_count":"0","engravings_char_count":"0","engravings_band":"10","stones":"[{\"stone_id\":\"27\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"132.80\",\"stone_y\":\"114.50\",\"stone_width\":\"71.60\",\"stone_height\":\"71.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"1\",\"stone_mm_width\":\"5.00\",\"stone_mm_height\":\"5.00\"},{\"stone_id\":\"28\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"100.50\",\"stone_y\":\"166.20\",\"stone_width\":\"36.20\",\"stone_height\":\"36.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"2\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"29\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"200.20\",\"stone_y\":\"105.10\",\"stone_width\":\"33.90\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"3\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"30\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"165.80\",\"stone_y\":\"82.50\",\"stone_width\":\"35.50\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"4\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"}]","images":"[{\"title\":\"white gold\",\"source\":\"Style4_4_W_M.png\"},{\"title\":\"yellow gold\",\"source\":\"Style4_4_Y_M.png\"}]"}
Update 2
Based on mikerobi's answer I was able to figure out what was happening:
Here is where I encoded it:
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row['stones'] = getStones($ring_id);
$row['images'] = getRingVariations($ring_id);
return json_encode($row);
But the functions getStones and getRingVariations were returning json_encode'd strings. I needed to change them to return plain strings.
Your JSON structure is wrong, it is wrapping stones in quotes, turning it into a string.
Your JSON looks like:
{
stones: "[{\"stone_id":\"27\"},{\"stone_id\":\"27\"}]"
}
It should look like:
{
stones: [{"stone_id": 27},{"stone_id": 27}]
}
EDIT
It appears you are converting all values to string, including numbers, I updated my example to reflect this.
Also, I'm guessing by the output that you are writing your own code to serialize the JSON, I highly recommend using an existing library.
It is recursive, but your input string (response) is not in correct format. Get rid of those escape characters (\") and try again.