admin管理员组

文章数量:1201982

I am trying to access a JSON field that has the key '*':

{ 
  "parse": { 
    "text": {
      "*": "text i want to access" 
    }
  }
}

Neither myObject.parse.text.* nor myObject.parse.text[0] works.

I have searched for an hour but haven't found any hint that an asterisk has special meaning. If I just traverse the complete tree and make String comparison with if (key == "*") I can retrieve the text, but I would like to access this field directly. How can I do that?

I am trying to access a JSON field that has the key '*':

{ 
  "parse": { 
    "text": {
      "*": "text i want to access" 
    }
  }
}

Neither myObject.parse.text.* nor myObject.parse.text[0] works.

I have searched for an hour but haven't found any hint that an asterisk has special meaning. If I just traverse the complete tree and make String comparison with if (key == "*") I can retrieve the text, but I would like to access this field directly. How can I do that?

Share Improve this question edited Dec 27, 2021 at 19:20 Dave Newton 160k27 gold badges258 silver badges307 bronze badges asked Sep 30, 2011 at 12:14 Peter Peter 1732 silver badges5 bronze badges 3
  • 10 Whoever designed that JSON string should be slapped around a bit. – user610217 Commented Sep 30, 2011 at 12:20
  • 2 you get this with the wikipedia api, for example de.wikipedia.org/w/… – simon Commented Apr 2, 2013 at 21:06
  • It is not pretty, but I could see this make sense in some kind of front-end translate module. Like when a standard string should be inserted when a certain translation key does not exist for a certain language. – iMe Commented Oct 25, 2017 at 13:50
Add a comment  | 

4 Answers 4

Reset to default 12
json.parse.text["*"]

Yucky name for an object member.


Asterisks have no special meaning; it's a string like any other.

myObject.parse.text.* doesn't work because * isn't a legal JS identifier. Dot notation requires legal identifiers for each segment.

myObject.parse.text[0] doesn't work because [n] accesses the element keyed by n or an array element at index n. There is no array in the JSON, and there is nothing with a 0 key.

There is an element at the key '*', so json.parse.text['*'] works.

Try use the index operator on parse.text:

var value = object.parse.text["*"];

try to use

var text = myObject.parse.text['*']

You could do:

var json = {"parse":
 {"text":
  {"*":"text i want to access"}
 }
}

alert(json.parse.text['*']);

本文标签: javascriptJSONAccess field named 39*39 asteriskStack Overflow