I don't understand why the test in jQuery's parseJSON function:
/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))
returns false
for the string:
{"TermTitle":"some Title"}
The test in http://www.jsonlint.com/ tells me that the string {"TermTitle":"some Title"}
is valid JSON, but when I try to pass it into $.parseJSON(opData)
the parseJSON
function fails...
I also tested just this /^[\],:{}\s]*$/.test...
function separately in Firebug with the mentioned string.
[edit] Ok, code:
var json = '{"TermTitle":"some Title"}';
var obj = $.parseJSON(json);
alert('obj = ' + obj + ' and obj.TermTitle = ' + obj.TermTitle);
works also for me.
But in my case where I have the following in my JavaScript:
function GetTerm($iInd) {
$.ajax({
type: "POST",
url: "get_term.php",
data: {
id: $iInd
},
success: function(data){
ProcessFetchedTerm(data);
}
});
//If I tried adding dataType: "json" then it would stop working at all.
}
function ProcessFetchedTerm(opData) {
alert ("In ProcessFetchedTerm, data: '" + opData + "'");
alert ("typeof opData: " + typeof opData);
alert ("Replacement result of the regex function: " +
opData.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").
replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
alert ("Result of the regex function: " +
/^[\],:{}\s]*$/.
test(opData.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").
replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
var oTerm = $.parseJSON(opData);
alert('oTerm = ' + oTerm + ' and oTerm.TermTitle = ' + oTerm.TermTitle);
}
and in get_term.php
I have:
echo json_encode(
array(
"TermTitle"=>"some Title"
)
);
The alerts return:
In ProcessFetchedTerm, data: '{"TermTitle":"some Title"}'
typeof opData: string
Replacement result of the regex function: {]:]}
Result of the regex function: false
The last alert is not shown
[edit 2]
I rewrote the beginning of my function ProcessFetchedTerm
to
function ProcessFetchedTerm(opData) {
var json = '{"TermTitle":"some Title"}';
alert ("In ProcessFetchedTerm, opData: '" + opData + "' json: '" + json + "'");
var oTerm = $.parseJSON(json);
the alert puts out:
In ProcessFetchedTerm, opData: '{"TermTitle":"some Title"}' json: '{"TermTitle":"some Title"}'
So the strings are equal and in case the next line is var oTerm = $.parseJSON(json);
it works but if next line is var oTerm = $.parseJSON(opData);
it does not work.
So what could be hidden inside this (presumably) string object opData
that prevents it from working?