Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将javascript对象转换为JSON_Javascript_Json - Fatal编程技术网

将javascript对象转换为JSON

将javascript对象转换为JSON,javascript,json,Javascript,Json,我有一个从PHP迁移到Node.js的应用程序。此应用程序将javascript对象作为数据发送到调用PHP处理程序的ajax函数 然后,PHP处理程序使用PHP的JSON_encode函数将对象转换为JSON。Node有一个名为“json_encode”的包,但它的工作原理与PHP对应的包不同 基本上,我想将其转换为: { 'pages[anycast][blocks][0][frames_content]': ' \n <section class="bg-white builder-

我有一个从PHP迁移到Node.js的应用程序。此应用程序将javascript对象作为数据发送到调用PHP处理程序的ajax函数

然后,PHP处理程序使用PHP的JSON_encode函数将对象转换为JSON。Node有一个名为“json_encode”的包,但它的工作原理与PHP对应的包不同

基本上,我想将其转换为:

{ 'pages[anycast][blocks][0][frames_content]': ' \n <section class="bg-white builder-bg padding-110px-tb xs-padding-60px-tb" . . . }

{'pages[anycast][blocks][0][frames\u content]:'\n编辑我会保留最初的答案,以防对其他人有用

如果您通过Ajax发送JSON,并检查
$\u POST['data']
,那么在PHP端需要做的就是
JSON\u解码($\u POST['data'])

此时,您将拥有一个PHP
stdClass
对象,其中包含您期望的所有字段,例如
$object->delete
或其他字段

如果希望使用关联数组而不是对象,请使用
json\u decode($\u POST['data'],true)

如果这仍然不是答案,也许您可以更好地详细说明什么是确切的输入,以及您期望的确切输出,正如我之前的答案所述,正是您描述的I/O


假设您正在接收的对象键中没有花哨的字符,比如内部键,如
'pages[anycast][blocks][0][frames\u content]
,您可以使用一些专门的约定将这些类型的键(通常来自旧的数据库或不知道JSON的服务)转换为更递归的数据

这只是一个例子:

const input={'pages[anycast][blocks][0][frames\u content]':'value'};
常量输出=Object.keys(输入).reduce(
(js,key)=>{
让root=js;
常量键=键
.替换(
/(\[\\]\[?)/g,
($0,$1)=>$1===']'?'':'\x01'
)
.split('\x01');
对于(设i=1,{length}=keys;i
序列化的
输出
变量在解析后如下所示:

{
“页数”:{
“选播”:{
“区块”:[
{
“框架内容”:“值”
}
]
}
}
}
当前示例假定放置在
[0]
[1]
中的任何内容都应作为数组处理,其他所有内容都应作为对象字段处理

建议的转换使每个索引也可以有多个条目:

const输入={
“页面[anycast][blocks][0][frames_content]”:“first”,
'页面[选播][块][1][帧内容]:'第二',
};
//…在上一次解析之后,输出将
{
“页数”:{
“选播”:{
“区块”:[
{
“框架内容”:“第一”
},
{
“框架内容”:“第二”
}
]
}
}
}

当然,如果您有两个相同的字段名,这些字段名将被覆盖,但我相信如果您的对象来自旧的服务,这种情况永远不会发生,因为我认为他们已经找到了自己的模式。

看起来您是在将其序列化为字符串,而不是对象。因此,这些额外的字符。您能为我们提供一些代码吗?Where是页面[选播][块][0][帧内容]正在生成-JS中的客户端,您正试图将其转换为JSON发送到PHP,或PHP中的服务器端,您正试图在JS中读取它?不要认为它直接回答了您的问题,但可能值得检查lodash的和函数。显示您的原始PHP代码和尝试替换它的Node.JS代码。然后我们可以显示you您在转换中出错的地方。您最初的转换看起来像是由PHP使用POST或GET参数完成的解析。我认为没有任何内置JS函数公开此解析,但它可能是在
请求
模块内部完成的。您的回答产生了以下结果:{pages:{anycast:{blocks:[Array]},错误:{blocks:[Array]},下载:{blocks:[Array]},检查:{blocks:[Array]},索引:{blocks:[Array]},语音:{blocks:[Array]},主页:{blocks:[Array]},牙科:{blocks:[Array]},callonly:{blocks:[Array]}我已经提供了一个答案,我有一点投入,如果有更好的投入,就会有一个更好的答案。你编辑后,我的答案,所以也许我会看看,看看我能做些什么。
{"pages":{"anycast":{"blocks":[{"frames_content":"            \n            <section class=\"bg-white builder-bg padding-110px-tb xs-padding-60px-tb\" . . .}
{ '{"data":{"pages":{"anycast":{"blocks":[{"frames_content":" \n <section class': '\\"bg-white builder-bg padding-110px-tb xs-padding-60px-tb\\" . . . }
var pages = {}, theSite;
            if( site.sitePages[0].blocks.length !== 0 ) {
                for( var x = 0; x < site.sitePages.length; x++ ) {
                    if( site.sitePages[x].blocks.length !== 0 ) {
                        pages[site.sitePages[x].name] = site.sitePages[x].prepForSave();
                    } else {                
                        pages[site.sitePages[x].name] = 'empty';
                    }
                }

                theSite = {
                    pages: pages
                };

            } else {
                theSite = {
                    delete: true
                };
            }

            //remove old alerts
            $('#errorModal .modal-body > *, #successModal .modal-body > *').each(function(){
                $(this).remove();
            });

            $.ajax({
                url: 'https://api.handler.com/save',
                method: 'POST',
                data: theSite,
                dataType: "json"
            }).done(function (res) {
                //enable button
                $("a#savePage").removeClass('disabled');
                if( res.responseCode === 0 ) {
                    if( showConfirmModal ) {
                        $('#errorModal .modal-body').html( res.responseHTML );
                        $('#errorModal').modal('show');
                    }
                } else if( res.responseCode === 1 ) {
                    //no more pending changes
                    site.setPendingChanges(false);
                    $('body').trigger('changePage');
                }
            });
        },

        /*
            preps the site data before sending it to the server
        */
        prepForSave: function(template) {
            this.sitePagesReadyForServer = {};
            if( template ) {//saving template, only the activePage is needed
                this.sitePagesReadyForServer[this.activePage.name] = this.activePage.prepForSave();
                this.activePage.fullPage();
            } else {//regular save
                //find the pages which need to be send to the server
                for( var i = 0; i < this.sitePages.length; i++ ) {
                    if( this.sitePages[i].status !== '' ) {
                        this.sitePagesReadyForServer[this.sitePages[i].name] = this.sitePages[i].prepForSave();
                    }
                }
            }
        },
<?php
$return = [];

if( isset($_POST['data']) && $_POST['data'] != '' ) {

    if( isset($_POST['data']['delete']) ) {

        $myfile = fopen("site.json", "w");
        fwrite($myfile, '{}');
        fclose($myfile);

    } else {

        $myfile = fopen("site.json", "w");
        fwrite($myfile, json_encode($_POST['data']));
        fclose($myfile);

    }

    $return['responseCode'] = 1;
    $return['responseHTML'] = '<h5>Hooray!</h5> <p>The site was saved successfully!</p>';

} else {

    $return['responseCode'] = 0;
    $return['responseHTML'] = '<h5>Ouch!</h5> <p>Something went wrong and the site could not be saved :(</p>';

}
echo json_encode($return);
?>