我试图在php中编码以下字符串,以便它可以作为JSON对象发送:
success:{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},
logout: {'type'='button', 'value'='logout', 'class'='logout-button'},
sessionID: {'type'='hidden', 'name'='sessionID', 'value'=1}
我如何格式化它以便使用json_encode()?
正确编码答案 0 :(得分:1)
{'success':{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},
'logout': {'type'='button', 'value'='logout', 'class'='logout-button'},
'sessionID': {'type'='hidden', 'name'='sessionID', 'value'=1}}
你只需要大括号(开头和结尾)就可以使它成为一个有效的JSON数组。
需要引用密钥。
答案 1 :(得分:0)
echo "var myAssociativeArray = [
success:{'id':'success=-message', 'class':'success-message', 'inner-html':'Congratulations! You have been succesfully logged in'},
logout: {'type'='button', 'value'='logout', 'class'='logout-button'},
sessionID: {'type'='hidden', 'name'='sessionID', 'value'=1}
];";
但是,好像你在PHP端创建了这个字符串(对吗?),这意味着你正在为它做json_encode
工作。相反,你应该有类似的东西:
//This is a temp array just to show you how it works:
$myArr = array(
"success" => ( object ) array(
"id" => "success=-message",
"class" => "success-message",
"inner-html" => "Congratulations! You have been succesfully logged in"
)
);
//Now you output the json version
echo json_encode( $myArr );