0

I've been developing a web application where I'm receiving data in this format, from a node server:

"{""elements":[{"10sr2b2":{"total":0,"bad":22,"clients":["fc8e7f","fc8e7e"],"zone":"101900"}}]}"

The poblem is this data is an array key-value called "elements" where "10sr2b2" is the key of the first element of the array.

So when I call $.parseJSON() method, this return an object like this:

elements: Array[1]
  0: Object
    10sr2b2: Object
       zone: "101900"
       clients: Array[2]
         0: "fc8e7f"
         1: "fc8e7e"
       length: 2
       __proto__: Array[0]
    bad: 22
    total: 0

Where "10sr2b2" it's supposed to be the key and it's an object and I need to get this value somehow.

Can you help me?

2
  • 1
    Your JSON has the format Object {"key": Array [Object {"key": Object {...}}]} just as you're seeing when you parse it. Whilst you can get find keys in Objects, it might suit your needs better to re-structure what the server is giving you into Object {"key": Array [Object {"key": "hash", "value": Object {...}}]}, and now you can use o.elements[i].key; and o.elements[i].value Commented Mar 24, 2014 at 14:06
  • I think it is a bad practice to have a key starting with number Commented Mar 24, 2014 at 14:07

3 Answers 3

1

You could use Object.keys to get the object keys.

var keys = Object.keys(data.elements[0]);
Sign up to request clarification or add additional context in comments.

Comments

0

Can you change the format from the node server? It needs to send something more like:

"{""elements":[{"key": "10sr2b2" "value": {"total":0,"bad":22,"clients":"fc8e7f","fc8e7e"],"zone":"101900"}}]}"

3 Comments

Hi, thanks for your contribute, unfortunately I can't change this format.
but could you transform the received data into this format before parsing?
No. This is example data. I'm expecting a lot of data and it would be impossible to transform the received data into this format.
0

If you know you'll always only have one key for each item, you can use a for..in loop that immediately breaks, for example

var i, key, obj = $.parseJSON(/*...*/);
for (i = 0; i < obj.elements.length; ++i) { // loop over elements
    for (key in obj.elements[i]) break; // get key
    // now can access
    obj.elements[i][key]; // Object
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.