开发者

Why can't I access JSON objects by key in JavaScript?

开发者 https://www.devze.com 2023-04-06 09:10 出处:网络
This is my JSON object: { text: \'stuff\', user: \'user1 } when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via cons

This is my JSON object:

{ text: 'stuff',
  user: 'user1
}

when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.

So how can I properly access everything in JavaScript?

I don't want to use 开发者_JAVA技巧jQuery as this is all node.js programming so it's serverside.

UPDATED - full JSON

{ text: '@junk_666 おかえりか',
  user: 
   { display_name: 'mono',
     screen_name: 'monochrm',
     klout_score: null,
     location_str: '画面の前',
     utc_offset: '32400' },
  venue_id: 1304409836517,
  match_type: 'twitter',
  tweet_id: '116494264137023489',
  created_at_unix: 1316609371,
  meta: 
   { matchedPhrase: 'junk',
     venueName: 'deletemepls really long name' },
  tags: [ '' ],
  indexed_at_unix: 1316609416 }


The json seems to be invalid

{
    "text": "stuff",
    "user": "user1"
}


I copied and pasted your object into a FireBug console and it recognized it.

If you need to count the number of key/value pairs, you can use a function such as this one to do it:

function numMembers(o) {
    var i=0;
    for (a in o) {
        i++;
    }
    return i;
}

You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.


First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.

Secondly, JavaScript objects in general do not have a length property. Arrays do.

There's no problem with your object literal so there must be some other problem elsewhere in your code.


Try this:

{ text: 'stuff',
  user: 'user1'
}

You left off an apostrophe.

Now that you've posted your full JS code (that's not JSON, as @josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号