在Javascript中从JSON中选择项

在Javascript中从JSON中选择项,javascript,json,Javascript,Json,我想从javascript中的JSON响应中选择一项。我正在调用一个GET请求,API正在返回JSON 获取API:-https://autocomplete.clearbit.com/v1/companies/suggest?query=google.com JSON:-[{“name”:“Google”,“domain”:“Google.com”,“logo”:https://logo.clearbit.com/google.com“}] 我想在函数外部选择name的值。这是我的Javasc

我想从javascript中的JSON响应中选择一项。我正在调用一个GET请求,API正在返回JSON

获取API:-
https://autocomplete.clearbit.com/v1/companies/suggest?query=google.com

JSON:-
[{“name”:“Google”,“domain”:“Google.com”,“logo”:https://logo.clearbit.com/google.com“}]

我想在函数外部选择
name
的值。这是我的Javascript

        var theUrl = 'https://autocomplete.clearbit.com/v1/companies/suggest?query=';
        var q = "google.com";
        function httpGet(theUrl, q)
       {
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open( "GET", theUrl+q, false ); // false for synchronous request
            xmlHttp.send( null );

            return xmlHttp.responseText;
       }

       var a = httpGet(theUrl, q);
       console.log(a.name);

但是,
a.name
正在返回
未定义的

您正在尝试读取字符串的
name
属性

要将JSON转换为JavaScript数据结构,必须对其进行解析(使用
JSON.parse()
方法)


完成后,需要查看数据结构的正确部分

JSON由一个数组组成,其中包含一个具有name属性的对象


您必须先从数组中提取对象,然后才能读取其名称属性。

您需要将来自google的响应解析为JSON,将其转换为对象,如下所示:

var theUrl = 'https://autocomplete.clearbit.com/v1/companies/suggest?query=';
var q = "google.com";

function httpGet(theUrl, q) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", theUrl+q, false ); // false for synchronous request
  xmlHttp.send( null );
  try {
    return JSON.parse(xmlHttp.responseText);
  } catch (error) {
    return null;
  }
}

var a = httpGet(theUrl, q);
if (a && a.length) {
  console.log(a[0].name);
} else {
  console.log('no results found');
}

Google还返回一个数组,因此您必须执行
a[0].name
而不是
a.name
,为了更好地衡量,我们将添加安全检查,以确保Google实际向我们返回JSON,并且在尝试打印名称之前,它实际上至少包含1项。

“同步请求为false”-危险:这是不推荐使用的功能,对站点有不利影响。不要这样做。@GeorgeJempty-这不是异步调用!是的,我在半天前取消了投票,但自动生成的评论仍然存在