将原始字符串转换为JSON格式

时间:2019-11-28 09:03:43

标签: arrays json

嗨,我只是有一个问题,如何将这个API响应转换为json数据。我尝试使用explode,但响应似乎分成了数组。

StatCode: 11
StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :

也许是这样

{

"StatCode": 11,
"StatName": "cancelled",
"OrderID": "OP_AFIFAH_6889",
"Amount": 1.10,
"TranID": 143519171
etc..
}

谢谢

3 个答案:

答案 0 :(得分:2)

最好的方法是更改​​API以返回JSON对象。如果您没有访问该API的权限,那么我为您编写了一个简单的JavaScript,可以将其转换为JSON对象:

function toJSON(input) {
    const lines = input.split('\n')
    const result = []

    for (let i = 1; i < lines.length; i++) {        
        if (!lines[i])
            continue;
        const obj = {}
        const currentline = lines[i].split(':')

        obj[currentline[0]] = currentline[1]
        result.push(obj)
    }
    return JSON.stringify(result)
}

console.log(toJSON(`StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :`)
);

答案 1 :(得分:0)

[
    {
        "StatName": "cancelled",
        "OrderID": "OP_AFIFAH_6889",
        "Amount": 1.10,
        "TranID": 143519171,
        "Domain": "test",
        "BillingDate": "2019-11-26 16:58:49",
        "BillingName": "test",
        "VrfKey": "test",
        "Channel": "credit",
        "Currency": "MYR",
        "ErrorCode": "CC_000",
        "ErrorDesc": "Successful Payment"
    }
]

注意:Amount和TranID值都是数字,如果您希望它们是字符串类型,请给它们加上双引号。 谢谢

答案 2 :(得分:-1)

从Web服务器接收数据时,数据始终是字符串。

使用JSON.parse()解析数据,该数据成为JavaScript对象。

let str = '{ "StatCode": "11", "StatName": "cancelled", "OrderID": "OP_AFIFAH_6889"}'

let obj = JSON.parse(str);

结果为{StatCode: "11", StatName: "cancelled", OrderID: "OP_AFIFAH_6889"}