You are trying to map clubs to two separate arrays (each containing a single object), rather than a single array with two objects.
json_clubs = {
"clubs": [
{
"Oak Club": {
"members": [
"Charles",
"Nora",
"Tom",
"Paul"
]
}
},
{
"Bravo Club": {
"members": [
"Nathaniel",
"Roselyn",
"Ash"
]
}
}
]
}
Answer from chepner on Stack OverflowVideos
You are trying to map clubs to two separate arrays (each containing a single object), rather than a single array with two objects.
json_clubs = {
"clubs": [
{
"Oak Club": {
"members": [
"Charles",
"Nora",
"Tom",
"Paul"
]
}
},
{
"Bravo Club": {
"members": [
"Nathaniel",
"Roselyn",
"Ash"
]
}
}
]
}
Rather than including the two club objects inside of the clubs array, you only adding the Oak Club object to it and then defining another array to the JSON object that is anonymous. Here's a better way to structure that code:
json_clubs = {
"clubs": [
{
"Oak Club": {
"members": [
"Charles",
"Nora",
"Tom",
"Paul"
]
}
},
{
"Bravo Club": {
"members": [
"Nathaniel",
"Roselyn",
"Ash"
]
}
}
]
}
storejson= getJSonObject("@ViewBag.JsonData");
function getJSonObject(value) {
return $.parseJSON(value.replace(/"/ig, '"'));
}
The data is not valid JSON, since \" in strings seems to have been replaced with "\.
Contact the author of that supposedly-JSON and notify him or her that there are plenty of JSON libraries available for all languages and platforms.
I faced the same issue, actually there are some hidden characters unseen and you need to remove it. Here's a global code that works for many cases:
<?php
$checkLogin = file_get_contents("http://yourwebsite.com/JsonData");
// This will remove unwanted characters.
// Check http://www.php.net/chr for details
for (
i <= 31; ++$i) {
$checkLogin = str_replace(chr(
checkLogin);
}
$checkLogin = str_replace(chr(127), "", $checkLogin);
// This is the most common part
// Some file begins with 'efbbbf' to mark the beginning of the file. (binary level)
// here we detect it and we remove it, basically it's the first 3 characters
if (0 === strpos(bin2hex($checkLogin), 'efbbbf')) {
$checkLogin = substr($checkLogin, 3);
}
$checkLogin = json_decode( $checkLogin );
print_r($checkLogin);
?>
Removing the BOM (Byte Order Mark) is often-times the solution you need:
function removeBOM($data) {
if (0 === strpos(bin2hex($data), 'efbbbf')) {
return substr($data, 3);
}
return $data;
}
You shouldn't have a BOM, but if it's there, it is invisible so you won't see it!!
see W3C on BOM's in HTML
use BOM Cleaner if you have lot's of files to fix.
As guys pointed in previous answers, there can be unprintable characters in json, which means they should be removed before calling json_decode.
One way to do that is this:
$json = preg_replace('/[[:^print:]]/', '', $json);
I am not saying this is the best solution, but so far the only one I found that worked for me.
As we found in the comments that there are invisible characters in the string, consider running this bit of code. It should show you each character in the string, it'd ascii value and it's printed version.
There should be a few characters in there which do not print anything; those are the ones preventing you from json_encoding the string. I cannot see why they are in the string, that has something to do with your database and the data you post into it, but at least you'll know where the problem is.
Odds are they are contained inside the inserted data somewhere, which means you probably have a piece of code somewhere that add something unprintable to their input.
You can strip them while exporting, but it would be better to find out which code adds them and remove them from the database. They will continue to bother you in the future otherwise. (As you've seen at this point even something simple like strlen() will fail to work properly due to these characters)
for( $i = 0 ; $i < mb_strlen($string) ; $i++ ) {
echo 'pos: ' . $i . ' | ord: ' . ord( $string[$i] ) . ' | char: ' . $string[$i] . '<br />';
}
For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.
e.g.
var d = "";
var json = JSON.parse(d);
or if you are using AngularJS
var d = "";
var json = angular.fromJson(d);
In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.
Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.
The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.
Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file
$("#register-form").submit(function (event) {
var entrance = $(this).find('input[name="IsValid"]').val();
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
if (request) {
request.abort(); // cancel if any process on pending
}
var postData = {
"objAskGrant": entrance,
"objPass": password,
"objNameSurname": namesurname,
"objEmail": email,
"objGsm": parseInt(gsm),
"objAdres": adres,
"objTerms": termsOk
};
$.post(formURL,postData,function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
});
event.preventDefault();
});
PHP Edit:
if (isset($_POST)) {
$fValid = clear($_POST['objAskGrant']);
$fTerms = clear($_POST['objTerms']);
if ($fValid) {
$fPass = clear($_POST['objPass']);
$fNameSurname = clear($_POST['objNameSurname']);
$fMail = clear($_POST['objEmail']);
$fGsm = clear(int($_POST['objGsm']));
$fAddress = clear($_POST['objAdres']);
$UserIpAddress = "hidden";
$UserCityLocation = "hidden";
$UserCountry = "hidden";
$DateTime = new DateTime();
$result = $date->format('d-m-Y-H:i:s');
$krr = explode('-', $result);
$resultDateTime = implode("", $krr);
$data = array('error' => 'Yükleme Sırasında Hata Oluştu');
$kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
$retval = mysql_query( $kayit, $conn ); // Update with you connection details
if ($retval) {
$data = array('success' => 'Register Completed', 'postData' => $_POST);
}
} // valid ends
}echo json_encode($data);
Hi everyone,
I'm a beginner in php and now i am currently facing an issue with a JSON syntax error in my PHP code. I've tried debugging it myself but can't seem to figure out what I'm doing wrong. Here's the part of the code where the error is coming , while this is the only code which makes the issue remaining code is correctly returning the json and my js is able to access it while in this function
function getPremiumItem($conn, $item_code)
{
$sql = "SELECT item_name, credits FROM premium_items WHERE item_code = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $item_code);
$stmt->execute();
$item_name = '';
$credits = 0;
$stmt->bind_result($item_name, $credits);
if ($stmt->fetch()) {
echo json_encode(['item_name' => $item_name, 'credits' => $credits]);
} else {
echo json_encode(['error' => 'Item not found']);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET['action'])) {
if ($_SERVER['action'] === 'getPremiumItem' && isset($_GET['item_code'])) {
$item_code = $_GET['item_code'];
getPremiumItem($conn, $item_code);
}
}
}error is coming SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
can anyone pls help me fix the issue
Here's the JSON:
{ "timestamp":"2021-07-19T15:42:53Z", "event":"Fileheader", "part":1, "language":"English\\UK", "Odyssey":false, "gameversion":"3.8.0.104", "build":"r269978/r0 " }Here's the 3v4l link of it not working: https://3v4l.org/4H2gS#v8.0.8
When I say "nothing else does" I mean any online JSON validator. They all say it's valid JSON. PHP just doesn't like it.
The Weird thing is, if I open a file with that string using `fgets` `json_decode($str, true)` works.
I have these strings in an array I'm looping over, and I get NULL every damn time. I've echoed out the fgets string and pasted it into json_decode, and still no luck.