简体   繁体   中英

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. 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:

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. I'd prefer if I didn't have to include the quotes in the JSON file. 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:

// 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.

(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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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