Greg Venech
Greg Venech

Reputation: 9090

How should I map numbers to text in JSON?

What is the best practice when it comes to mapping numbers to text in JSON? A JavaScript map would be perfect as I can use numbers for keys, which I can't do with objects:

let map = new Map();

map.set(1, 'describe 1');
map.set(2, 'describe 2');

... and so on. However you can't use maps in json, as far as I know. Is the best option really just to use an array of arrays?

[
  [ 1, 'describe 1' ],
  [ 2, 'describe 2' ]
]

Upvotes: 1

Views: 1307

Answers (3)

deltree
deltree

Reputation: 3824

JSON stands for "JavaScript Object Notation" and is a subset of Javascript--specifically the subset that is used for writing out objects. The map you're typing creates an object. That object that the map.set function outputs is what you're getting at. You can see it by doing this.

let map = new Map();

map.set(1, 'describe 1');
map.set(2, 'describe 2');
console.log(JSON.stringify(map));

I think that you want your numbers to be strings, in which case you can do this:

let map = new Map();

map.set('1', 'describe 1');
map.set('2', 'describe 2');

However, if your numbers are intended to identify the indexes of items on an array, you might be going for this:

[null, 'describe 1', 'describe 2']

Either way, you'll be able to see it with JSON.stringify

For more evidence, here's what Chrome outputs with your inputs:

> let map = new Map();
undefined
> map.set(1, 'describe 1');
Map {1 => "describe 1"}
> map.set(2, 'describe 1');
Map {1 => "describe 1", 2 => "describe 1"}

Which would look like:

{ 1: 'describe 1', 2: 'describe 2' }

as a Javascript Object (i.e. JSON)

For more information on JSON, check out http://www.json.org/

Upvotes: 4

tex
tex

Reputation: 2766

There are several ways to do this that will work in JSON.

Use an object with the numbers, converted to strings, as keys (as Weston describes, above): {'1':'describe 1', '2': 'describe 2'}

Or an object with the text as keys: {'describe 1':1, 'describe 2':2}

Or an array created such that the indexes match the numbers paired with the text at that position in the array: [,'describe 1', 'describe 2']

Upvotes: 1

Weston
Weston

Reputation: 1451

You could just use the string value "1", "2", and so on as keys in your JSON file, and then call parseInt on them if you want to get the number value. You could then write a function that converts your imported JSON file into a Map. Something like

function JSONtoMap(src){
  var m = new Map();
  for(var key in src)
    m.set(parseInt(key), src[key])
  return m;
}

Upvotes: 3

Related Questions