如何在 javascript 中获得 json 键和值?

我返回一个 json,如下所示

{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

我试图得到每个元素的键和值:

..
}).done(function(data){
alert(data['jobtitel']);
});

我得到 undefined在警报。为什么? 我尝试 data.jobtitel,我尝试循环,但没有成功..。

539728 次浏览
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);


//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

you have parse that Json string using JSON.parse()

..
}).done(function(data){
obj = JSON.parse(data);
alert(obj.jobtitel);
});

http://jsfiddle.net/v8aWF/

Worked out a fiddle. Do check it out

(function() {
var oJson = {
"name": "",
"skills": "",
"jobtitle": "Entwickler",
"res_linkedin": "GwebSearch"
}
alert(oJson.jobtitle);
})();
var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}


var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

A simple approach instead of using JSON.parse

 success: function(response){
var resdata = response;
alert(resdata['name']);
}

You can use the following solution to get a JSON key and value in JavaScript:

var dt = JSON.stringify(data).replace('[', '').replace(']', '');
if (dt) {
var result = jQuery.parseJSON(dt);
var val = result.YOUR_OBJECT_NAME;
}

For getting key

var a = {"a":"1","b":"2"};
var keys = []
for(var k in a){
keys.push(k)
}

For getting value.

var a = {"a":"1","b":"2"};
var values = []
for(var k in a){
values.push(a[k]);
}

It looks like data not contains what you think it contains - check it.

let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};


console.log( data["jobtitel"] );
console.log( data.jobtitel );