简体   繁体   English

如何从json对象访问和使用多个数据? 我需要做一个数组吗?

[英]How to access and use multiple data from json object? Do I need to make an array?

I am a beginner and using $.get to retrieve data from a rest API such as: 我是一个初学者,使用$ .get从其余的API中检索数据,例如:

 [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},
  {"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}
  {"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}] }


$.get('http://xxxxxxxxxxx,
      function (data) {
      var obj = $.parseJSON(data);

So from what I understand I have retrieved the data from the REST API and parsed it so it is stored in a variable called obj. 因此,据我了解,我已经从REST API中检索了数据并进行了解析,因此将其存储在一个名为obj的变量中。

My question is, how do I access and use each unique record in the obj variable? 我的问题是,如何访问和使用obj变量中的每个唯一记录?

Each record has it's own picture (item1.jpg, item2.jpg etc). 每个记录都有其自己的图片(item1.jpg,item2.jpg等)。 Whem my app loads I want it to show the item1.jpg image, and I want to be able to navigate to the other item pictures using buttons (previous / next). Whem我的应用程序加载我希望它显示item1.jpg图像,并且我希望能够使用按钮(上一个/下一个)导航到其他项目图片。 I also want the description and price to be displayed underneath in some text input fields. 我还希望描述和价格显示在某些文本输入字段的下方。

What I have figured so far is that I should: 到目前为止,我认为我应该:

  1. Iterate through the obj variable, and store each record into an array. 遍历obj变量,并将每个记录存储到数组中。
  2. Upon app initialisation I can set the default value for the image placeholder to array[index0].url, and set the description and price fields. 应用初始化后,我可以将图像占位符的默认值设置为array [index0] .url,并设置说明和价格字段。
  3. I can then set the previous and next buttons to array[currentIndex-1] or array[currentIndex+1]. 然后,我可以将上一个和下一个按钮设置为array [currentIndex-1]或array [currentIndex + 1]。

Would this be the best way to do it? 这将是最好的方法吗?

Or can I just do this without using an array and manipulate the obj.data directly? 还是可以不使用数组就直接执行obj.data来做到这一点?

Thanks!!! 谢谢!!!

I may not be understanding what exactly what you want to do but I think I have the gist. 我可能不明白您到底想做什么,但我想我有主旨。 If you just want to show the picture then the array of just images probably wouldn't be a bad idea. 如果您只想显示图片,则仅包含图像的数组可能不是一个坏主意。 However, it looks like the Jason you're getting is already in an array. 但是,看起来您得到的Jason已经存在于数组中。 You can just use array index notation to get to what you want. 您可以只使用数组索引符号来获得所需的内容。

ie) 即)

var arr = //your json response ;
var current = 0; //sets currently displayed object to the first in the array
var setCurrent = function () {
  var image = arr[current]["url"];
}

You can then modify current however you want (on click on arrow iterate up/down, etc) then call the setCurrent function to set your image the the one you want. 然后,您可以根据需要修改电流(单击箭头向上/向下迭代),然后调用setCurrent函数将图像设置为所需的图像。 Hope that helps! 希望有帮助!

You can use the response you have from $.get() directly. 您可以直接使用$.get()的响应。
It is an array of objects. 它是一个对象数组。

You can use it like this: 您可以像这样使用它:

console.log(data[2].description);
// outputs: "Console"

I've made a CodePen demo where it has a 4th object with a real image url to show you how to use the url info... 我制作了一个CodePen演示,其中有一个带有真实图像URL的第4个对象,向您展示如何使用URL信息...




EDIT 编辑

Just in case you wouldn't know this: 以防万一您不知道这一点:

You can use the response inside the scope of the $.get() callback... 您可以在$.get()回调范围内使用响应...
You can not use it straith after the $.get() outside the callback since $.get() is asynchronous. 您不能在回调之外的$.get()之后直接使用它,因为$.get()是异步的。

You can use it in some other handler wich will happen after the response is received. 您可以在收到响应后将在其他处理程序中使用它。

 var getResponse; $.get('http://xxxxxxxxxxx', function (data) { getResponse = data; console.log(data[2].description); // outputs: "Console" console.log(getResponse[2].description); // outputs: "Console" }); console.log(getResponse[2].description); // outputs: "Undefined" // But since this handler will be triggered long after the response is obtained: $("#somebutton").click(function(){ console.log(getResponse[2].description); // outputs: "console" }); 

In order for your page javascript to be able to access the data retrieved from your ajax request, you'll need to assign it to some variable which exists outside the callback function. 为了使页面javascript能够访问从ajax请求中检索到的数据,您需要将其分配给回调函数之外的某个变量。

You will need to wait until the ajax request has been processed before you can read the array. 您将需要等到ajax请求已处理后才能读取数组。 So you might want to set the actual default image to be something that doesn't rely on the ajax request (a local image). 因此,您可能希望将实际的默认图像设置为不依赖ajax请求的内容(本地图像)。

Here's a simple approach 这是一个简单的方法

 // fake testing ajax func function fakeget (url, callback) { setTimeout(callback(JSON.stringify([ {"id":"1","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item1.jpg","price":"99","description":"Mobile Phone"}, {"id":"2","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item3.jpg","price":"92","description":"Console"} ])), 1000); } // real code starts here // global variables for ajax callback and setImg func to update var imageData, currentImg; // change this back to $.get for real fakeget('http://xxxxxxxxxxx', function (data) { imageData = $.parseJSON(data); setImg(0); } ); function setImg(index) { // turns negative indices into expected "wraparound" index currentImg = (index % imageData.length + imageData.length) % imageData.length; var r = imageData[currentImg]; $("#theImg").attr('src', r.url); $('#theDescription').text(r.price + " " + r.description); } $("#prev").click(function () { setImg(currentImg - 1); }); $("#next").click(function () { setImg(currentImg + 1); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <img id='theImg' src='somedefault.jpg'> <div id='theDescription'></div> </div> <button id='prev'>Prev</button> <button id='next'>Next</button> 

Few observations : 很少观察到:

  • Your JSON Object is not a valid JSON . 您的JSON Object不是有效的JSON
  • No need to parse it again your data is already a JSON Object . 无需再次parse它,您的data已经是一个JSON Object

Working fiddle 工作提琴

 var data = [{"id":"1","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item1.jpg","price":"99","description":"Mobile Phone"},{"id":"2","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\\/\\/123.456.78.910\\/workforce\\/images\\/item3.jpg","price":"92","description":"Console"}]; for (var i in data) { var imgUrl = data[i].url; console.log(imgUrl); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 JSON 对象访问数据? - how do I access data from JSON object? 我如何将 json 对象作为 json 数组 - How do i make json object as an json array 如何在“使用严格”模式下跨多个节点模块将对象数组作为数据存储访问? - How do I access my object array as a datastore across multiple node modules in 'use strict' mode? 如何在 JS 中从这个 json 访问 json object 元素? - How do I access json object elements from this json in JS? 如何访问这个 Javascript 数组(JSON object?)? - How do I access this Javascript array (JSON object?)? 如何从 json-server 托管的 API 访问数组中的对象 - How do I access an object in an array from an API hosted by json-server 如何从匹配某个键的 JSON object 创建一个数组? - How do I make an array from a JSON object that matches a certain key? 我如何使用angularjs从json数组访问数组? - How do i access array from json array using angularjs? 如何使用JSON.parse的reviver函数向数组中的每个对象添加数据? - How do I use `JSON.parse`'s reviver function to add data to each object in an array? 如何访问另一个 JSON 对象数组中的 JSON 对象数组的第一个元素? - How do I access first element of JSON object array that is in another JSON object array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM