简体   繁体   中英

Json key and value in javascript

My Link json test file is the following:

[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]

The javascript requesting the value, using axios:

var Links = './Links'

axios.get(Links)
 .then(function(response){
  console.log(response.data["google"]);
  try {
    var Test12 = JSON.stringify(response.data["google"]);
  } catch (err) {
    var Test12 = 'nothing'
  }

The result is undefined.

My goal is to return the value of the input "google" or any input from the JSON and store it in the var as a string.

Since its an array of objects so you should access the values like,

response.data[0].google

OR

response.data[0]["google"]

Your data file is a list with two objects in it.

To access the google item you should access the list element.

var Test12 = JSON.stringify(response.data[0]["google"]);

Although I would change the json file to:

{"google" : "https://google.com", "bing" : "https://bing.com"}

Maybe like this:

 var data=[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]; data.forEach(function(el, index) { Object.keys(el).forEach(function(val) { console.log(val + " => " + el[val]); }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM