如何将JSON Blob转换为列和值

时间:2018-01-31 11:47:35

标签: mysql json

我有一个VP/MS MySQL表,其中“ref”列包含唯一标识符和“请求”列,本质上包含BLOB格式的完整JSON响应消息。消息如下所示:

{
    "vars": {

    },
    "computes": {
        "P_PRERefId_str": {
            "=": "12421321"
        },
        "P_PolicyNumber_str": {
            "=": "1234567890"
        },
        "P_YearlyPolicyFeeAmt_rea": {
            "=": "70.56"
        }
    }
}

有没有办法可以以某种方式将JSON键值对提取为3列和相应的值,如:

P_PRERefId_str   P_Policy    P_YearlyPolicyFeeAmt_rea
12421321         1234567890  70.56

1 个答案:

答案 0 :(得分:0)

这可能就是你要找的东西。首先,将您的JSON转换为PHP对象。

$myObject = json_decode('{
    "vars": {},
    "computes": {
        "P_PRERefId_str": {
            "=": "12421321"
        },
        "P_PolicyNumber_str": {
            "=": "1234567890"
        },
        "P_YearlyPolicyFeeAmt_rea": {
            "=": "70.56"
        }
    }
}');

然后,迭代"计算"属性并将属性插入数据库。

foreach ($myObject->computes as $column => $attr) {
    foreach ($attr as $equalSign => $val) {
    // INSERT $val INTO $column
    // Depending on your Driver (PDO, framework ORM)
    // Your code will differ here
}};