Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Will JSON Evolve to Have Native Support for Ecmascript Map Objects?

Are there any formal proposals, in progress, that address a backwards-compatible evolution to JSON's current treatment of Map objects?

For example, let say you want to convert a Map to JSON and then write it to file:

let map = new Map();
map.set(1, "A");
map.set(2, "B");
map.set(3, "C");

// Convert map to an "array of 2-element arrays":
let arrayFromMap = [... map];

let json = JSON.stringify(arrayFromMap);
writeJSONtoFile(json,"path/to/jsonFile.json");

So now we have a JSON file sitting on the disk. The issue is that, the code that ultimately reads this file has no knowledge that it contains a Map object unless we give that code-file that awareness. There is nothing inherent in JSON to explicitly indicate Map instead of a "array of 2-element arrays". For example, code not having this awareness might do this:

let json = readJSONfromFile("path/to/jsonFile.json");
let parsedJSON = JSON.parse(json);
console.log(parsedJSON); // outputs an "array of 2-element arrays"

However, if the the code writer gives the code awareness (that the original type was a Map) the file can be converted back to a Map:

let json = readJSONfromFile("path/to/jsonFile.json");
let map = new Map(JSON.parse(json));

This same awareness isn't necessary for these built-ins: Objects and Arrays.

In the example above, this "awareness" requirement isn't too burdensome. However, imagine a large hierarchy that contains both Maps and "arrays of 2-element arrays" that are not intended to be Maps. This "awareness burden" has now extended to each nested Map within the hierarchy.

Are there any formal proposals, in progress, that address a backwards-compatible evolution to JSON's current treatment of Map objects?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, because JSON notation, while it originated with Javascript, is widely used in a very large number of languages, but a Javascript Map only has meaning within the context of Javascript.

Any sort of change to JSON notation to allow for the serialization and deserialization of objects that only have meaning in Javascript would make that JSON format incompatible with most other languages.

This isn't to say that a custom parser based on JSON couldn't be written to properly serialize and deserialize Maps, but such a thing would only be based on JSON, rather than being an addition to the JSON standard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...