How to represent an array with empty elements in JSON?

房东的猫 提交于 2019-12-12 05:12:58

问题


I have an array in JavaScript that looks like this:

var pattern = [ ["C5", 3], , , , , , , , ["C5", 3], , , ] 

I want to store it in a json file like this:

{
  "pattern": [
               ["C5", 3], , , , , , , , ["C5", 3], , ,
             ]
}

JSONLint tells me this:

Parse error on line 6:
...        ],        ,        ,        
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

So I understand I can't let the space between commas empty. What's similar to empty, but is accepted by JSON standards?

This pattern file is part of a Javascript Music Tracker I'm making that's similar to impulse tracker, and I want the json file to be as clean as possible.


回答1:


If you want to have empty space in JSON, you should fill it with null.

Example:

var pattern = [ ["C5", 3], null, null, null, null, null, null, null, ["C5", 3], null, null, null, null, ...... ]



回答2:


If you don't want to use null with a sparse array, you could use the object representation of an array.

 pattern = [["C5", 3], , , , , , , , ["C5", 3], , , ]

... would be replaced by an object with index value as properties and an additional length property:

parse_array = {
    0: ["C5", 3],
    8: ["C5", 3],
    length: 12
}

This object can be generated from the array using its reduce method:

parse_array = pattern.reduce( ( obj, val, i ) =>
  {
    obj.length++
    if ( val )
      obj[i] = val
    return obj
  }, { length: 0 } )

Then it's easy to convert the object into a JavaScript Array, using a simple arrow function:

pattern = Array.from( parse_array, v => v )

//Encode array

var pattern = [["C5",3],null,null,null,null,null,null,null,["C5",3],null,null,null]

out.innerHTML = JSON.stringify( pattern ) + "\n"

var parse1 = pattern.reduce( ( obj, val, i ) =>
  {
    obj.length++
    if ( val )
      obj[i] = val
    return obj
  }, { length } )

out.innerHTML += JSON.stringify( parse1 ) + "\n"


//Decode object

var parse2 = {
  0: ["C5", 3],
  8: ["C5", 3],
  length: 12
}

out.innerHTML += JSON.stringify( parse2 ) + "\n"

out.innerHTML += JSON.stringify( Array.from( parse2,  v => v ) )  + "\n"
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
  <title></title>
</head>
<body>
	<h3>JSON array with empty items</h3>
	<pre id="out"></pre>
</body>
</html>


来源:https://stackoverflow.com/questions/30585552/how-to-represent-an-array-with-empty-elements-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!