javascript - 从 jQuery 中的字符串解析 JSON

标签 javascript jquery json

http://localhost/project1/index.php

//AJAX region
$(function(){
	$.ajax({
		type : 'GET',
		url : 'https://jsonplaceholder.typicode.com/posts/1',
		success : function(data){
			console.log('success \n', data);
		},
		error : function(data){
			console.log('error', data);
		}
	});
});//AJAX region
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

可以轻松地从 http://localhost/project1/json.php 加载数据
安慰: enter image description here

数据是字符串,如果我使用 $.parseJSON(data) 或 JSON.parse(data) 我会收到以下错误... enter image description here enter image description here

我希望数据作为实时 JSON 对象,以便我可以访问每个属性和值。

最佳答案

观察1:不必要的parseJSON

无需调用parseJSON。 使用 $.ajaxdataType 属性直接以 JSON 格式加载数据:

$.ajax({
    type : 'GET',
    dataType: 'json', // here
    url : 'http://localhost/project1/region.php',
    success : function(data) {
        // data is already a JS object :)
        console.log('success \n', data);
    },
    error : function(data){
        console.log('error', data);
    }
});

观察 2:错误的 JSON

上面的代码仍然会抛出相同的错误,因为

unexpected token ,

它指的是对象及其子对象的所有最后元素之后的尾随逗号。删除该逗号,就不会再出现错误。

例如:

"State1" : {
    "City 1",
    "City 2",
    "City 3",
}

“City 3”后不应有逗号。对于其他州以及整个 "country2" 对象也是如此。

还有另一个错误:您的 States 对象是数组,但您将其编写为对象。将 "State1""State2" 的大括号更改为方括号。

关于javascript - 从 jQuery 中的字符串解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48931269/

相关文章:

javascript - React 和 Bootstrap Javascript

jquery - knockout - 取消变更事件?

python - 使用Python合并两个json文件

javascript - Three.js - 在运行时更改 JSON Material

javascript - Angular Ui.router $state 模板 ng-models 是 $rootScope

javascript - ins1.addEventListener 不是函数

javascript - Google map 对我不起作用

Javascript - 文本延迟显示(缓入)

jquery 不能从外部 symfony 包工作

javascript - 如何在JS中根据子值获取父级JSON对象