For JSON is it bad to use punctuation like “-” in the key names?

后端 未结 1 852
执念已碎
执念已碎 2021-01-13 18:32

Is it true that punctuation in property keys can cause developer usability issues in languages such as Ruby which uses symbolic hash key and in Javascript, these characters

相关标签:
1条回答
  • 2021-01-13 18:52

    The JSON Specification doesn't explicitly forbid using hyphens or any other characters in the name/value pairs of objects.

    Whether it's a great idea is another, but most languages have no trouble dealing with special characters as the key, e.g. JavaScript:

    var x = {"a-b": "hello"};
    console.log(x['a-b']); // prints "hello"
    

    Because a-b is not a valid property name x.a-b would not work as expected, but JavaScript has an alternative syntax for object dereferencing by using [] notation.

    Another example, PHP:

    $x = json_decode('{"a-b": "hello"}');
    echo $x->{'a-b'};
    

    Again, $x->a-b would not work, so PHP supports dereferencing using ->{} notation.

    0 讨论(0)
提交回复
热议问题