将JSON对象写入服务器上的.json文件
我试图将我的JSON对象写入服务器上的.json文件。我现在做这个的方法是:将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
} ,
任何想法,为什么我得到所有这些斜线的,为什么它是所有在同一行?
感谢, 斯托伊奇
你是双重编码。没有必要在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
}
?>
应该不是fwrite($ file,$ json); ?? – Francesco 2011-05-14 04:33:35
不要JSON.stringify
。通过这样做你会得到一个双JSON编码。
您首先将数组元素转换为JSON字符串,然后将它们添加到完整对象中,然后编码您的大对象,但是当对已编码的元素进行编码时,将被视为简单字符串,因此所有特殊字符被逃脱。你需要有一个大对象,并且只需编码一次。编码器会照顾孩子。
对于行问题尝试发送JSON数据类型标头:Content-type: text/json
我认为(没有谷歌它)。但渲染将仅取决于您的浏览器。也可以使用缩进进行编码。
<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"
}
]
}
evrything你需要在一个文件中,这是我生活中写过的最无效的代码,但它解决了我们的问题! – 2016-08-23 01:58:18
可能为时已晚来回答题。但是我遇到了同样的问题。我用“JSON_PRETTY_PRINT”
以下是我的代码解决它:
<?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";
}
?>
您使用的框架或前手在POST进行任何消毒,尽量在PHP ini和重启转弯magic_qoutes。 – RobertPitt 2010-10-13 12:23:04