JSON Attribute Best Practice - javascript

Usually, what I see is {"attribute":241241}
but writting this does exactly the same thing : {attribute:241241}.
Is {attribute:241241} considered bad practice and should be avoided or not?

{attribute:241241} does not validate using JSONLint, so yes, it is bad practice and should be avoided.
Further, if you look at the JSON spec at json.org, you will find that for objects the first value is always a string (indicated by double quotes).

You are confusing JSON with Object literal syntax, in Javascript doing
var o = {
"attribute":241241
};
is not JSON, but object literal. And yes, the quotes are useless there.

The JSON specification requires that keys be quoted, so the second form isn't valid JSON.
As Snakes and Coffee noted, it is a valid Javascript object literal (on which JSON is based), and some JSON parsers will accept it anyway. So it may work in some cases, but sooner or later you'll run into a perfectly functional JSON parser that rejects your non-quoted keys because they aren't valid per the spec.

As per the specification here, the names in name/value pairs must be of type string.
An object is an unordered collection of zero or more name/value pairs,
where a name is a string and a value is a string, number, boolean,
null, object, or array.

Related

Dust JS Dot Into string Key Name

I'm not sure if I'm doing something wrong, but I have "dates" as a key for the object and Dust seems to just output exactly what I put in rather than evaluate properly.
{#.weeks pos=items}
{pos['2016-02-15].id}
{/.weeks}
Output:
{pos.'2016-02-15'.id}
How can I output the ID rather than output the string?
Dust does not allow the character - as part of an array key.
As you mentioned in your comment, - is allowed in Dust references, but the rules are slightly different.
Dust references must not start with a number, and contain the characters 0-9a-zA-Z_$-. This mirrors the rules for real Javascript variables, except for the hyphen.
Array keys are allowed to start with numbers, but cannot contain hyphens. So when you use a date as part of the key, Dust uses the array key evaluation path since the date starts with a number.
This would work, for example, using the array-key evaluation path:
{#.weeks pos=items}
{pos[20160215].id}
{/.weeks}
And so would this, because it uses the reference evaluation path:
{#.weeks pos=items}
{pos[date-2016-02-15].id}
{/.weeks}
You'll have to munge your data slightly.
I think you've uncovered an inconsistency in the way Dust handles reference naming. In early Dust, references were only allowed to be valid JS variable names. This restriction was relaxed later on but there are clearly some rough bits around it.

Why is JSON.parse so picky with quotes?

Basically, I am trying to create an object like this by providing a string to JSON.parse():
a = {x:1}
// -> Object {x: 1}
Intuitively I tried:
a = JSON.parse('{x:1}')
// -> Uncaught SyntaxError: Unexpected token x
After some fiddling I figured out:
a = JSON.parse('{"x":1}')
// -> Object {x: 1}
But then I accidentally changed the syntax and bonus confusion kicked in:
a = JSON.parse("{'x':1}")
//-> Uncaught SyntaxError: Unexpected token '
So now I am looking for an explanation why
one must to quote the property name
the implementation accepts single quotes, but fails on double quotes
The main reason for confusion seems to be the difference between JSON and JavaScript objects.
JSON (JavaScript Object Notation) is a data format meant to allow data exchange in a simple format. That is the reason why there is one valid syntax only. It makes parsing much easier. You can find more information on the JSON website.
Some notes about JSON:
Keys must be quoted with "
Values might be strings, numbers, objects, arrays, booleans or "null"
String values must be quoted with "
JavaScript objects on the other hand are related to JSON (obviously), but not identical. Valid JSON is also a valid JavaScript object. The other way around, however, is not.
For example:
keys and values can be quoted with " or '
keys do not always have to be quoted
values might be functions or JavaScript objects
As pointed out in the comments, because that's what the JSON spec specifies. The reason AFAIK is that JSON is meant to be a data interchange format (language agnostic). Many languages, even those with hash literals, do not allow unquoted strings as hash table keys.

Why are JSON attribute names quoted? [duplicate]

According to Crockford's json.org, a JSON object is made up of members, which is made up of pairs.
Every pair is made of a string and a value, with a string being defined as:
A string is a sequence of zero or more
Unicode characters, wrapped in double
quotes, using backslash escapes. A
character is represented as a single
character string. A string is very
much like a C or Java string.
But in practice most programmers don't even know that a JSON key should be surrounded by double quotes, because most browsers don't require the use of double quotes.
Does it make any sense to bother surrounding your JSON in double quotes?
Valid Example:
{
"keyName" : 34
}
As opposed to the invalid:
{
keyName : 34
}
The real reason about why JSON keys should be in quotes, relies in the semantics of Identifiers of ECMAScript 3.
Reserved words cannot be used as property names in Object Literals without quotes, for example:
({function: 0}) // SyntaxError
({if: 0}) // SyntaxError
({true: 0}) // SyntaxError
// etc...
While if you use quotes the property names are valid:
({"function": 0}) // Ok
({"if": 0}) // Ok
({"true": 0}) // Ok
The own Crockford explains it in this talk, they wanted to keep the JSON standard simple, and they wouldn't like to have all those semantic restrictions on it:
....
That was when we discovered the
unquoted name problem. It turns out
ECMA Script 3 has a whack reserved
word policy. Reserved words must be
quoted in the key position, which is
really a nuisance. When I got around
to formulizing this into a standard, I
didn't want to have to put all of the
reserved words in the standard,
because it would look really stupid.
At the time, I was trying to convince
people: yeah, you can write
applications in JavaScript, it's
actually going to work and it's a good
language. I didn't want to say, then,
at the same time: and look at this
really stupid thing they did! So I
decided, instead, let's just quote the
keys.
That way, we don't have to tell
anybody about how whack it is.
That's why, to this day, keys are quoted in
JSON.
...
The ECMAScript 5th Edition Standard fixes this, now in an ES5 implementation, even reserved words can be used without quotes, in both, Object literals and member access (obj.function Ok in ES5).
Just for the record, this standard is being implemented these days by software vendors, you can see what browsers include this feature on this compatibility table (see Reserved words as property names)
Yes, it's invalid JSON and will be rejected otherwise in many cases, for example jQuery 1.4+ has a check that makes unquoted JSON silently fail. Why not be compliant?
Let's take another example:
{ myKey: "value" }
{ my-Key: "value" }
{ my-Key[]: "value" }
...all of these would be valid with quotes, why not be consistent and use them in all cases, eliminating the possibility of a problem?
One more common example in the web developer world: There are thousands of examples of invalid HTML that renders in most browsers...does that make it any less painful to debug or maintain? Not at all, quite the opposite.
Also #Matthew makes the best point of all in comments below, this already fails, unquoted keys will throw a syntax error with JSON.parse() in all major browsers (and any others that implement it correctly), you can test it here.
If I understand the standard correctly, what JSON calls "objects" are actually much closer to maps ("dictionaries") than to actual objects in the usual sense. The current standard easily accommodates an extension allowing keys of any type, making
{
"1" : 31.0,
1 : 17,
1n : "valueForBigInt1"
}
a valid "object/map" of 3 different elements.
If not for this reason, I believe the designers would have made quotes around keys optional for all cases (maybe except keywords).
YAML, which is in fact a superset of JSON, supports what you want to do. ALthough its a superset, it lets you keep it as simple as you want.
YAML is a breath of fresh air and it may be worth your time to have a look at it. Best place to start is here: http://en.wikipedia.org/wiki/YAML
There are libs for every language under the sun, including JS, eg https://github.com/nodeca/js-yaml

Is '""' a valid JSON string?

I am confused. To quote json.org
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most
languages, this is realized as an array, vector, list, or sequence.
So, I don't think '""' should be a valid JSON string as its neither a list values(i.e. does not start with '[' and ends with ']') but JSON.parse doesn't give exception and returns empty string.
Is it a valid JSON string.
No, '' is not valid JSON. JSON.parse('') does throw an error – just look in your browser console.
Next time you have an "is this valid JSON?" question, just run it through a JSON validator. That's why they exist.
So, I don't think "" should be a valid JSON string
It is a valid JSON string (which is a data type that may appear in a JSON text).
as its neither a list values(i.e. does not start with '[' and ends with ']')
A JSON text (i.e. a complete JSON document) must (at the outermost level) be…
(Here I cut the original answer because the specification has been revised).
A JSON text is a serialized value.
(quoting the JSON specification
So "" is a valid JSON text. This wasn’t the case when the original version of this answer was written. Some JSON parsers may break when the outer most value is not an object or array.
The original answer (which is now incorrect resumes here):
…either an object or an array. A string is not a valid JSON text.
The formal specification says:
A JSON text is a serialized object or array.
But back to quoting the question here:
but JSON.parse doesn't give exception and returns empty string.
The JSON parser you are using is being overly-liberal. Don't assume that all JSON parsers will be.
For example, if I run perl -MJSON -E'say decode_json(q{""})' I get:
JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this) at -e line 1.
Following the newest JSON RFC 7159, "" is in fact valid JSON. But in some earlier standards it wasn't.
Quote:
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.
A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array.
Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.
2023 Update
The other answers on this question are outdated and contain some incorrect information. The most recent JSON specification is RFC 8259, which obsoletes the previous RFCs referenced here. It says:
Note that certain previous specifications of JSON constrained a JSON text to be an object or an array.
A string by itself is therefore valid as an entire JSON text. It doesn't need to be contained within an outer object construct. The examples section of the RFC shows this:
Here are three small JSON texts containing only values:
"Hello world!"
42
true
The content of the string of course is irrelevant, so an empty string by itself is acceptable.
Note: JSON requires that strings be quoted with " so single quotes are still not valid:
"" // Valid
'' // Invalid

Javascript String operations

Javascript has a number of string manipulation operations which can be performed on it. So we have methods like concat(), slice(), match(), etc
My question is do all these string manipulation methods return a new string value as the result OR are there some methods which actually modify the actual string being used in the method ?
Strings in JavaScript (and many other languages) are implemented as immutable objects. This has a few beneficial properties:
It's thread safe, and more specifically,
Multiple references to the same string can be kept safely without having to worry that the value changes.
This also means that all string methods must return a new string if they aim to modify the original value.
The return value is a clone of the original string.
In other words, calling concat, match or slice will not modify the original string.
You can always refer to the MDN reference for documentation
But, to quote from the source
Concat
Combines the text of two or more strings and returns a new string.
Strings are immutable, and once they are created they even cannot be modified again.
Mdn:
Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string, for example, a substring of the original (by picking individual letters or using String.substr()) or a concatenation of two strings using the concatenation operator (+) or String.concat().
Therefore, yes. Every String operation returns a new String

Categories