如何在PHP中正确编码json(双引号问题)


How to correctly encode json in PHP (double quotes issue)

我正在尝试从Wordpress自定义字段创建一个有效的JSON。我在这里遇到了问题:

{"eu_price":"400", // this one is ok
 "other_prices":["{'"GBP'":'"330'",'"USD'":'"525'"}"] // this is not
}

我该如何摆脱那些斜杠?

我正在使用Wordpress函数从MySql数据库字段中获取数据:

$my_product[other_prices] = get_post_meta( $product_id, '_regular_currency_prices', false );

然后我使用:

echo json_encode($my_product, JSON_UNESCAPED_SLASHES);

以便返回编码的结果。

在数据库中,字段内容如下:

{"GBP":"330","USD":"525"}

完整的json响应是:

{"user_country":"US","title":"Dress  1960","permalink":"http://site.dev/my_slug/","eu_price":"350","other_prices":["{'"GBP'":'"290'",'"USD'":'"460'"}"],"main_image":"http://doublej.dev/wp-content/uploads/2015/01/1100000003274_0-300x300.jpg"}

设置$my_product['other_prices']时,将其设置为字符串。如果数据库包含JSON,则需要对其进行解码,以便在对响应进行重新编码时,一切都有意义。

$jsonEncodedData = get_post_meta( $product_id, '_regular_currency_prices', false );
$my_product['other_prices'] = json_decode($jsonEncodedData)

不要手动构建json字符串,使用json_encode:

echo json_encode([
        'eu_price'=>'400',
        'other_prices'=>[
            'GBP'=>'330',
            'USD'=>'525'
        ]
    ]);