简体   繁体   English

是否需要在 json 文件中包含键的引号?

[英]Prevent the need for including quotes for keys in json files?

I have a very large JSON data file that I am including in my program.我的程序中包含一个非常大的 JSON 数据文件。 The format of the file looks like this:该文件的格式如下所示:

{
  "2":{"x":0,"y":0,"w":16,"h":16},
  "3":{"x":5,"y":9,"w":7,"h":12},
  "4":{"x":2,"y":5,"w":12,"h":11},
  ...
}

And I include it like so:我像这样包括它:

import * as colliders from "../assets/colliders.json";

The issue is that it seems to require the use of quotes in the keys.问题是它似乎需要在键中使用引号。 That is, if I try to instead make the data file formatted like such (no quotes):也就是说,如果我尝试改为使数据文件格式如下(不带引号):

{
  2:{x:0,y:0,w:16,h:16},
  3:{x:5,y:9,w:7,h:12},
  4:{x:2,y:5,w:12,h:11},
  ...
}

Then I get the following error when compiling my Typescript:然后在编译我的 Typescript 时出现以下错误:

Error TS1327: String literal with double quotes expected.

I could just force there to be quotes, but it increases the file size by 33% or so.可以强制使用引号,但它会使文件大小增加 33% 左右。 I'd prefer if I didn't have to include the quotes in the JSON file.如果我不必在 JSON 文件中包含引号,我会更喜欢。 Is this possible?这可能吗? Or is it better practice to keep the quotes despite the file size increase?还是在文件大小增加的情况下保留引号是更好的做法?

You could make the file not a .json file, but a JavaScript or TypeScript file, and do something like:您可以使该文件不是.json文件,而是 JavaScript 或 TypeScript 文件,并执行以下操作:

// colliders.ts
export const colliders = {
  2:{x:0,y:0,w:16,h:16},
  3:{x:5,y:9,w:7,h:12},
  4:{x:2,y:5,w:12,h:11},
  // ...
}
import { colliders } from "../assets/colliders.ts";

But the extra space required by key delimiters is still almost certainly not something to worry about in a real application.但是,在实际应用程序中,键分隔符所需的额外空间几乎可以肯定是不必担心的。

If you really really care about space, and given that it seems that you always have the same columns (X, Y, W, H), I would store all the colliders inside a CSV file, then create a routine to read the file and build a JSON in memory from it.如果您真的很在意空间,并且考虑到您似乎总是有相同的列(X、Y、W、H),我会将所有对撞机存储在 CSV 文件中,然后创建一个例程来读取文件并从中构建 JSON 在 memory 中。

(I am not sure if you can access to the file system in your code, but that would be the direction in which I would be headed). (我不确定您是否可以在代码中访问文件系统,但这将是我前进的方向)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM