How to handle hyphen/minus sign in json?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • paragpdoke
    New Member
    • Dec 2007
    • 62

    How to handle hyphen/minus sign in json?

    Hello All.
    I am new to json and need to work with some json output generated by code which is outside my control. I was trying out some simple alert examples.

    Noticed that the hyphen or minus sign runs into problems. While this seems JavaScript wise logical (variable names cannot have operators), I don't know how to handle them.

    Here is my made up example that does not work:
    Code:
    <html>
    <head>
    <script language="JavaScript">
    var o={
      "parent-object":   {
        "child-object01":     {
          "name": "Anne"
        },
        "child-object02":     {
          "name": "John"
        },
        "child-object03":     {
          "name": "Julia"
        },
        "name": "Andrew"
      }
    };
    
    </script>
    </head>
    <body>
    	<a onclick="JavaScript:alert(o.parent-object.child-object01.name);">Click me</a>
    </body>
    If I replace all hyphens with underscores, then the alert does display "Anne".

    How does one handle such cases when the json input cannot be changed ?
    I tried searching on bytes for an answer, but the closest match I found was for double quotes. Here is the link to it:
    http://bytes.com/topic/javascript/answers/911058-json-object-escape-sequence-double-quotes-problem
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    Hello,

    If you access the JSON object like it is an associative array you can work around this.
    Code:
    <html>
    <head>
    <script language="JavaScript">
    var o={
      "parent-object":   {
        "child-object01":     {
          "name": "Anne"
        },
        "child-object02":     {
          "name": "John"
        },
        "child-object03":     {
          "name": "Julia"
        },
        "name": "Andrew"
      }
    };
     
    </script>
    </head>
    <body>
        <a onclick="javascript:alert(o['parent-object']['child-object01']['name']);">Click me</a>
    </body>

    Comment

    • paragpdoke
      New Member
      • Dec 2007
      • 62

      #3
      Perfect! Many thanks JKing.
      Regards,
      Parag Doke

      Comment

      Working...