访问对象的JSON数组的元素 [英] Access to elements of JSON array of objects

查看:82
本文介绍了访问对象的JSON数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器上的数据是对象的JSON数组形式.如果要打印第一个对象,如何访问第一个对象?数据格式为:

My data on server is in the form of JSON array of objects. If I want to print the first object, how can I access its first object? Format of data is:

[
  {
   "eventId": "8577",
   "datasetId": "34",
   "nodeId": "8076",
   "typeId": "4",
   "type": "TempAndHum",
  "status": "Temp : 35, Hum : 83",
  "datasetName": "test active set",
  "mode": "shared",
  "xmlFragment": "Absent",
  "gpsLat": "-23.549999",
  "gpsLong": "-46.633301",
  "contributor": "SanatIITD",
  "addedOn": "2015-04-21 08:03:16",
  "updatedOn": "2015-04-21 08:03:16"
  },
 {
  "eventId": "8576",
  "datasetId": "34",
  "nodeId": "8076",
  "typeId": "4",
  "type": "TempAndHum",
  "status": "Temp : 34, Hum : 81",
  "datasetName": "test active set",
  "mode": "shared",
   "xmlFragment": "Absent",
  "gpsLat": "-23.549999",
  "gpsLong": "-46.633301",
  "contributor": "SanatIITD",
  "addedOn": "2015-04-21 08:03:11",
 "updatedOn": "2015-04-21 08:03:11"
 },
 {
    "eventId": "8575",
   "datasetId": "34",
   "nodeId": "8076",
   "typeId": "4",
   "type": "TempAndHum",
   "status": "Temp : 33, Hum : 80",
   "datasetName": "test active set",
   "mode": "shared",
  "xmlFragment": "Absent",
  "gpsLat": "-23.549999",
   "gpsLong": "-46.633301",
   "contributor": "SanatIITD",
  "addedOn": "2015-04-21 08:03:05",
  "updatedOn": "2015-04-21 08:03:05"
 },
]

我尝试使用data [0],但最终打印"[".我也尝试使用JSON.stringify,然后用,"分割,但这给了我对象的第一个元素,而不是整个第一个对象.我需要打印在花括号内的整个第一个对象.有什么方法可以访问数组并通过执行document.getElementById("Id")= myData [0]来访问,所以不需要分别打印花括号中的所有元素.请给我一些解决方案.预先感谢.

I tried with data[0], but end up with printing "[". I tried with JSON.stringify also and then split with "," but that gives me first element of the object, not the whole first object. I need to print the whole first object which is within the curly braces. Is there any way so that I can access like array and by doing document.getElementById("Id")=myData[0], so that I don't need to print all elements within the curly braces separately. Please suggest me some solution. Thanks in advance.

推荐答案

首先使用var dataArray = JSON.parse(dataString), 您的数据目前是一个字符串.

use var dataArray = JSON.parse(dataString) first, your data is a string at the moment.

然后使用dataArray[0]

这篇关于访问对象的JSON数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆