On database: { "email", "color" }
But when I try to output it using application/json' => \yii\web\Response::FORMAT_JSON, the string contains extra slashes
[
"Verify",
"{ \"email\", \"color\" }"
]
I know that I can sort of use the replace() but can someone enlighten me on this scenario?
the encode add the slashes for prevent improper quotes sequence that break the corret use of content
whitout slashes you have in yoru case
"{ "email", "color" }" // that is not correctly formateed
you have already quote around you value in database.. and you data are already in json format so so you could use without encode
#webDav almost has the correct answer.
It appears you are incorporating the data from the database into another data structure. So you will need to parse the JSON from the database first, then include that data in your data before encoding again.
You are not retrieving raw string (similar to JSON) from the DB, but it is a string that needs to be converted to JSON in order to have meaning.
It seems to me that you are trying to encode an already json encoded data.
As a results it escapes the characters.
You have 2 options:
Do not format it to JSON again
Decode the data with json_decode() before return
If you need to append or combine that json data, then #2 is your only option
Related
I have the following code that converts json into an array:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
$jarray = json_decode($decodedstr, true);
echo "<pre>";
print_r($jarray);
echo "</pre>";
but my $jarray keeps returning null... I dont know why this is happening.. i have already validated my json in this question:
validated json question could anyone tell me what i am doing wrong? or what is happening. Thanks in advance.
when i echo my $str i get the following:
You are passing to json_decode a string that is not valid JSON, this is the reason NULL is returned.
As I see from comments inspecting the error code generated gives 4 that corresponds to the constant JSON_ERROR_SYNTAX that just means the JSON string has a Syntax Error.
(See http://php.net/manual/en/function.json-last-error.php)
You should inspect (echo) what you get from
$str = file_get_contents('http://localhost/data.json');
(You may edit your answer and post it - or a portion of it)
For sure it is not valid JSON; the problem lies there: in data.json.
Then as you fix things and get from data.json what is expected I would ensure you really need to use html_entity_decode on the fetched data.
It would be "weird" to have html encoded JSON data.
UPDATE
Looking at what you get from data.json it seem the JSON data contains actually HTML entities (as I see the presence of s)
This is actually weird, the right thing to do would be to fix how data.json is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json.
We can't deepen this here as I don't know where does data.json come from or the code that generates it. Eventually you may post another answer.
So here is a quick fix provided that the right approach would be what I just suggested above.
As you decode html entities, non breaking spaces turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data.
The idea is to remove these characters; your code becomes:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
// the character sequence for decoded HTML
$nbsp = html_entity_decode( " " );
// remove every occurrence of the character sequence
$decodedstr = str_replace( $nbsp, "", $decodedstr );
$jarray = json_decode($decodedstr, true);
from php manual
http://php.net/manual/en/function.json-decode.php
Return:
... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit
So, surely the JSON string passed to json_decode() is not valid:
maybe because of html_entity_decode
I have JSON data called rowdata that I use in an ajax call. If I use:
JSON.stringify(rowdata)
it looks like like the following:
{"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"}
I do send it to php and use a GET statement (Joomla's
JRequest::getVar("Description", "", "", "")
statement) to get the elements of rowdata but I cannot succeed.
If I look at the ajax data that has been send I do have the following:
rowdata%5BDescription%5D=qwerty
etc. after applying:
$.param(data)
I have used many version instead of "Description", but to no avail. I tried to get rowdata on its own and access its elements, but no success. I cannot find out what the %5B and %5D means, searching for that is problematic with the % sign. Anyone who can help to get the values of Description, Code, etc. in php?
You are sending JSON, but trying to parse it as application/x-www-form-urlencoded data.
Don't convert the object to JSON.
$.get('example.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});
I believe %5B is [ and %5D is ]. Your URL is encoding special characters. It's called URL encoding.
Do not use JSON if you want to push data with get... otherwise it will be encoded to satisfy JSON format and you will get those entities.
$.get('target.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});
I wanted to ask that in a php script of mine which I am accessing through an ajax request, I am returning json data ( converted from an array ) as such
echo json_encode($row_array);
I get this data in jquery and display it in a form. Do i need to apply htmlspecialchars / htmlentites before returning the data?
Is do then whats the correct way to do it? The following code gives me an error:
echo htmlentities(json_encode($row_array));
Thanking you
Imran
Do not apply htmlentities in this way. You should walk the array before json encoding it and escape each element, then json encode the array of safe-to-display values. In your usage json is just a transport layer for the array. You are not displaying the json array, just the element data. Don't escape transport layers--it could make the json string invalid.
Context is important.
You don't need to escape the data at all on the server side if it's going into a form input's value if you are using jQuery's val() function to populate it.
Example: http://jsfiddle.net/Y6TWv/1/
var data = '<strong>STRONG TEXT</strong>';
$('input').val(data); // output is escaped
$('p').text(data); // output is escaped
$('p').html(data); // output is not escaped
In addition, if you were to escape the data, don't do it like this:
// escapes the entire json string, not good - quotes will be broken
echo htmlentities(json_encode($row_array));
You would have to escape each item of $row_array first before json encoding it, either with array_map after the array is built, or as you're building the array.
In general, you should prefer htmlspecialchars over htmlentities, but it's not likely you need either one.
I just had a problem with single quotes in a JSON array. Chrome doesn't like single quotes in a JSON response returned via ajax. I escaped each value with htmlspecialchars(, ENT_QUOTES).
$theoptions['MemberList'] = array();
while($row = mssql_fetch_assoc($result)) {
$memberelement = array(
'Display'=> htmlspecialchars($row['FullName'], ENT_QUOTES),
'Value' => $row['ID']);
$theoptions['MemberList'][] = $memberelement;
}
header('Content-Type: application/json');
echo json_encode($theoptions);
I have the following JSON formatted string:
{
"hooks":[
{
"type":"subscribe",
"id":1331741592.6925,
"email":"JoeX#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\":\"Joe\",\"last_name\":\"X\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
},
{
"type":"subscribe",
"id":1331741592.7067,
"email":"JaneY#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\": \"Jane\",\"last_name\":\"Y\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
}
]
}
I want to use the PHP json_decode() function to put it in an associative array.
When I do run the script, debugging shows the value of the new array as null, so I presume the decode is failing. We aren't running PHP 5.3, so I can't use json_last_error(). Here is the code:
$hooks = (the JSON string from above);
$hooksArray = json_decode($hooks, true);
Any ideas why the $hooksArray is coming back null?
Is the JSON string inside your PHP source? Perhaps it's not interpreting the escaped backslashes correctly.
I tried the following experiment in Python for reference: Dumped the JSON data into a multi-line string via the REPL and decode it with json.loads(). It choked on the in-string quotes in the first instance of the custom_fields string. When I examined the multi-line string, all the escapes were gone, leaving me only with the quotes.
When I put the same JSON data in an external file and loaded it, it worked fine.
I put the JSON data in an external file and replaced all '\"' instances with '\\"' and then the first experiment started to work.
Maybe that will work for you too.
I am storing this {background:"default.jpg"} in the database in field of tables as i am taking the table fields data and makint the json by json_encode while encoding this json also get encoded and it is not valid json so how should i encode these json.
{"id_session":"c72b0581e7675b596a7651a7bb906438","gibid":"54","name":"Market Place","type":"S","num_owners":"0","inner_template":"","inner_data":"{background:\"default.jpg\"}","outer_template":"","o
it is adding the slashes how should i get return the valid json.
thanks.
Don't store JSON in the database, store it in a neutral format, like key/value columns. Or:
Decode the JSON, merge it into the array to be encoded, then encode it.
$data = array('id' => ...);
$data['inner_data'] = json_decode($databaseJson, true);
json_encode($data);
So you have a JSON string in the database and then you get it out of it and do a json_ecnode on ir again? For php you are just encoding some string (thats why the backslashes on the quotations marks are coming from).
But to achieve what you actually want, you could to decode the JSON string from the database first and then encode it with the rest of your data again.