我正在创建一个插件,用户可以在HTML的data-属性中添加自定义设置.设置是JSON格式的.我在Javascript中使用这些设置.

它有preview,basepaths处房产.previewbase具有字符串值,但是paths是由path个对象组成的array.

It works fine when i add JSON setting directly into the HTML:

<div data-side="front" data-params='{"preview": "assets/img/products/tshirt/front-preview.png", "base": "assets/img/products/tshirt/front-base.png", "paths": "[{\"name\": \"base\", \"path\": \"M 324.00,33.00 C 324.00,33.00\", \"x\": 92, \"y\": 16, \"height\": 370}, {\"name\": \"collar\", \"path\": \"M 358.00,46.10 C 358.00,46.10\", \"x\": 170, \"y\": 17, \"height\": 21}, {\"name\": \"leftSleeve\", \"path\": \"M 633.17,170.00 C 633.17,170.00\", \"x\": 288, \"y\": 66, \"height\": 131}, {\"name\": \"leftCuff\", \"path\": \"M 595.00,438.00 C 615.47,438.23\", \"x\": 293, \"y\": 172, \"height\": 33}, {\"name\": \"rightSleeve\", \"path\": \"M 142.00,140.00 C 143.46,150.28\", \"x\": 47, \"y\": 64, \"height\": 131}, {\"name\": \"rightCuff\", \"path\": \"M 48.00,375.38 C 48.00,375.38 95.00\", \"x\": 41, \"y\": 166, \"height\": 36}]"}'>

I'm getting this value using data('Params') method of jQuery. Its type is object.

Now, when i'm trying to json_encode a php array and pass it to the data-, it's added successfully

<div data-side="front" data-params=<?php echo "'".json_encode($dataParams)."'"; ?>>

But now typeof data('Params') in Javascript is string. So, i'm getting a JSON parse error. If i remove paths key, its type changes to object.

下面是我正在编码的数组的print_r:

Array
(
    [preview] => assets/img/products/tshirt/front-preview.png
    [base] => assets/img/products/tshirt/front-base.png
    [paths] => Array
        (
            [0] => Array
                (
                    [name] => base
                    [path] => M 324.00,33.00 C 324.00,33.00
                    [x] => 92
                    [y] => 16
                    [height] => 370
                )
                ... and more path arrays

        )

)

So, why does it changes its type to string if i include paths key? Any way to solve it?

编辑:

以下是输出:

Output

推荐答案

You need to escape data and handle special characters.

<div data-side="front" data-params="<?php echo htmlspecialchars(json_encode($dataParams), ENT_QUOTES, 'UTF-8'); ?>">

And get it with jQuery:

$('[data-side="front"]').data('params'); // object

或javascript

JSON.parse(document.querySelector('[data-side="front"]').dataset.params); // object

Json相关问答推荐

Bash和echo命令出现意外结果

通过在织女星简化图上裁剪来显示文本

在AWS步骤函数中将字符串解析为JSON&S映射状态

Postgres Select json数组并重新映射属性名称

用于参考的Jolt变换

在Jolt中将具有嵌套元素的对象数组转换为单独的对象列表

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

使用 jolt 变换展平嵌套 JSON - 非常复杂

取消嵌套数组并将数组名称添加为附加字段

JOLT 在 struct 体中间添加一个 JSON 字段

Jolt - 在同一级别添加时组合值的问题

如何从 rails 中的 respond_to 方法生成 json?

如何从 JSON 对象中获取日期

IE8 原生 JSON.parse 错误导致堆栈溢出

如何将 LinkedHashMap 转换为自定义 java 对象?

JSON对象中的JavaScript递归搜索

如何向(JSON)对象的原型添加方法?

如何在spark 上将json字符串转换为数据帧

使用 axios 在 POST multipart/form-data 请求中发送文件和 json

在 iPhone 上解析 JSON 日期