如何格式化JSONP响应的文本内容

时间:2016-03-14 03:34:14

标签: jquery jsonp

我有一个保存到文本文件的JSON字符串,我无法弄清楚通过JSONP返回格式的确切方法。 原始档案:

[{
    "id": "659",
    "recordtype": "inventoryitem",
    "columns": {
        "itemid": "100-mens-suit",
        "displayname": "Mens Mid Grey 2 reg Suit",
        "salesdescription": "Mens Mid Grey 2 reg Suit",
        "type": {
            "name": "Inventory Item",
            "internalid": "InvtPart"
        },
        "baseprice": 699,
        "internalid": {
            "name": "659",
            "internalid": "659"
        }
    }
}]

因为我必须手工准备,格式正确

callback(
    [{
        "id": "659",
        "recordtype": "inventoryitem",
        "columns": {
            "itemid": "100-mens-suit",
            "displayname": "Mens Mid Grey 2 reg Suit",
            "salesdescription": "Mens Mid Grey 2 reg Suit",
            "type": {
                "name": "Inventory Item",
                "internalid": "InvtPart"
            },
            "baseprice": 699,
            "internalid": {
                "name": "659",
                "internalid": "659"
            }
        }
    }]
)

callback({
    [{
        "id": "659",
        "recordtype": "inventoryitem",
        "columns": {
            "itemid": "100-mens-suit",
            "displayname": "Mens Mid Grey 2 reg Suit",
            "salesdescription": "Mens Mid Grey 2 reg Suit",
            "type": {
                "name": "Inventory Item",
                "internalid": "InvtPart"
            },
            "baseprice": 699,
            "internalid": {
                "name": "659",
                "internalid": "659"
            }
        }
    }]
})

我似乎无法在任何JSON格式工具中使用它,但我希望这是因为没有对JSONP进行验证。

非常感谢任何提示

1 个答案:

答案 0 :(得分:0)

如果要从文本文件中读取它,则需要在进入回调之前使用JSON.parse() - 如果您只是将其写入回调,我个人会这样声明:

var obj = {
    "id": "659",
    "recordtype": "inventoryitem",
    "columns": {
        "itemid": "100-mens-suit",
        "displayname": "Mens Mid Grey 2 reg Suit",
        "salesdescription": "Mens Mid Grey 2 reg Suit",
        "type": {
            "name": "Inventory Item",
            "internalid": "InvtPart"
        },
        "baseprice": 699,
        "internalid": {
            "name": "659",
            "internalid": "659"
        }
    }
};

callback(obj);

出于好奇,你的某些int被包裹成字符串是有原因的吗?