JSON.parse无法将JSON字符串转换为JSON对象

时间:2017-08-05 07:46:26

标签: javascript json angular typescript

需要帮助将JSON字符串转换为JSON对象.Even字符串JSON是有效的json(由https://jsonlint.com/验证)。

JSON:

{
    "condition": "AND",
    "rules": [{
            "id": "amount",
            "operator": "greater_or_equal",
            "value": "900"
        },
        {
            "condition": "AND",
            "rules": [{
                    "id": "vendorname",
                    "operator": "equal",
                    "value": "US BANK NATIONAL ASSOCIATION"
                },

                {
                    "id": "vendorname",
                    "operator": "equal",
                    "value": "HANSEN SOLUTIONS  LLC"
                }
            ]
        }
    ]

}

3 个答案:

答案 0 :(得分:3)

您的JSON字符串是多行的。应使用模板文字存储多行字符串,否则使用字符串连接来表示字符串。

以下例子使用模板文字。它用于表示多行字符串。



var str = `{
	"condition": "AND",
	"rules": [{
			"id": "amount",
			"operator": "greater_or_equal",
			"value": "900"
		},
		{
			"condition": "AND",
			"rules": [{
					"id": "vendorname",
					"operator": "equal",
					"value": "US BANK NATIONAL ASSOCIATION"
				},

				{
					"id": "vendorname",
					"operator": "equal",
					"value": "HANSEN SOLUTIONS  LLC"
				}
			]
		}
	]
}`;

console.log(JSON.parse(str));




这是一个单行字符串。



var str = '{"condition":"AND","rules":[{"id":"amount","operator":"greater_or_equal","value":"900"},{"condition":"AND","rules":[{"id":"vendorname","operator":"equal","value":"US BANK NATIONAL ASSOCIATION"},{"id":"vendorname","operator":"equal","value":"HANSEN SOLUTIONS  LLC"}]}]}';

console.log(JSON.parse(str));




答案 1 :(得分:2)

  

需要帮助将以下JSON字符串转换为JSON object.Even字符串   JSON是有效的json(由https://jsonlint.com/验证)。

JSON.parse(jsonString); 只要您需要合理的现代浏览器,它就是纯粹的JavaScript方法。

另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

更新: 试试JSON.parse(JSON.stringify(TheString))

答案 2 :(得分:0)

只需使用

try {
      let obj = JSON.parse( string);
} catch( e) {
    // conversion fails
   console.error( e ) 
}