我正在尝试将我的JSON对象写入服务器上的.json文件。我现在这样做的方式是:
JavaScript的:
function createJsonFile() {
var jsonObject = {
"metros" : [],
"routes" : []
};
// write cities to JSON Object
for ( var index = 0; index < graph.getVerticies().length; index++) {
jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
}
// write routes to JSON Object
for ( var index = 0; index < graph.getEdges().length; index++) {
jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
}
// some jQuery to write to file
$.ajax({
type : "POST",
url : "json.php",
dataType : 'json',
data : {
json : jsonObject
}
});
};
PHP:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = fopen('new_map_data.json','w+');
fwrite($file, $info);
fclose($file);
?>
写得很好,信息似乎是正确的,但它没有正确呈现。它出现了:
{"metros":["{\\\"code\\\":\\\"SCL\\\",\\\"name\\\":\\\"Santiago\\\",\\\"country\\\":\\\"CL\\\",\\\"continent\\\":\\\"South America\\\",\\\"timezone\\\":-4,\\\"coordinates\\\":{\\\"S\\\":33,\\\"W\\\":71},\\\"population\\\":6000000,\\\"region\\\":1}",
......但我期待着这个:
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} ,
我知道为什么我会得到所有这些斜线以及为什么它都在一条线上?
谢谢, 赫里斯托斯
答案 0 :(得分:18)
你是双重编码。不需要在JS 和 PHP中编码,只需在一侧进行编码,只需执行一次。
// step 1: build data structure
var data = {
metros: graph.getVerticies(),
routes: graph.getEdges()
}
// step 2: convert data structure to JSON
$.ajax({
type : "POST",
url : "json.php",
data : {
json : JSON.stringify(data)
}
});
请注意,dataType
参数表示预期的响应类型,而不是您将数据发送的类型。发布请求默认发送为application/x-www-form-urlencoded
。
我认为你根本不需要那个参数。你可以将其减少到:
$.post("json.php", {json : JSON.stringify(data)});
然后(在PHP中)执行:
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_map_data.json','w+');
fwrite($file, $json);
fclose($file);
}
else
{
// user has posted invalid JSON, handle the error
}
?>
答案 1 :(得分:5)
不要JSON.stringify
。这样做可以获得双JSON编码。
您首先将数组元素转换为JSON字符串,然后将它们添加到完整对象,然后对大对象进行编码,但在编码时,已编码的元素将被视为简单字符串,因此所有特殊字符串都是如此字符被逃脱。你需要有一个大对象并只编码一次。编码器将照顾孩子。
对于on行问题,请尝试发送JSON数据类型标题:Content-type: text/json
我认为(没有google for it)。但渲染仅取决于您的浏览器。也可以用缩进编码。
答案 2 :(得分:2)
回答这个问题可能为时已晚。但我遇到了同样的问题。我通过使用&#34; JSON_PRETTY_PRINT&#34;
解决了这个问题以下是我的代码:
<?php
if(isset($_POST['object'])) {
$json = json_encode($_POST['object'],JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Object Not Received";
}
?>
答案 3 :(得分:0)
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
的 data.json 强>
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}