简体   繁体   English

使用PHP将包含JavaScript对象的字符串转换为JSON字符串

[英]convert a string containing JavaScript object to a JSON string with PHP

This is the javascript Object (just a small part of it): 这是javascript对象(只是其中的一小部分):

dataToReturn = {
        "dimensionsDisplayType"  : [
            "dropdown","swatch",
        ],
        "pwEnabledDimensionMap" : {

            "size_name": true,

            "color_name": true

        },
        "isPWBadgeEnabled" : true,
        "isImmersiveExperience" : false,
        "isTabletWeb" : false
}

So in PHP it will look like: 因此,在PHP中它将如下所示:

<?php
    $jsObjStr = '{
            "dimensionsDisplayType"  : [
                "dropdown","swatch",
            ],
            "pwEnabledDimensionMap" : {

                "size_name": true,

                "color_name": true

            },
            "isPWBadgeEnabled" : true,
            "isImmersiveExperience" : false,
            "isTabletWeb" : false
    }';

But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of 但是如果我们想用json parse解析它,我们就不能在PHP中使用,因为它不是干净的JSON格式,因为

"dimensionsDisplayType"  : [
            "dropdown","swatch",
        ]

The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much. 包含诸如“ dimensionsDisplayType”之类的对象的键可能是不可预测的,因此使用regex进行清理不会有太大帮助。

The one that works is 有效的是

JSON.stringify(dataToReturn)

But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. 但就我而言,我无法运行客户端代码,因此必须使用PHP在服务器端将其转换为正确的JSON格式。 I was searching a lot online but I got not any satisfying function or library. 我在网上搜索了很多东西,但没有任何令人满意的功能或库。

How can this be solved ? 如何解决呢?

您可以尝试使用此正则表达式清理字符串,这将查找逗号,后跟可选的空格和close],然后将其替换为内容减去逗号。

$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM