在javascript中将JSON数组中的字符串转换为另一个数组

时间:2014-12-07 22:31:37

标签: javascript arrays json

我正在尝试移植以下代码以使用JSON文件http://malamas.com/jsuc/jsuc.html 目前我已设法采用“单位”和“因子”部分:

property[0] = "Acceleration";
unit[0] = new Array("Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)");
factor[0] = new Array(1, .3048, 9.806650, .01, 2.54E-02);

并将它们放入JSON行:

var text = '{"Accelleration": { "unit":"\\"Meter/sq.sec (m/sec^2)\\", \\"Foot/sq.sec (ft/sec^2)\\", \\"G (g)\\", \\"Galileo (gal)\\", \\"Inch/sq.sec (in/sec^2)\\"", "factor":"1, .3048, 9.806650, .01, 2.54E-02"}}'
var obj = JSON.parse(text);

我可以输出像这样的字符串

"Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)"

但我希望能够通过这样做将其提供给顶级代码:

property[0] = "Acceleration";
unit[0] = new Array(obj.Accelleration.unit);
factor[0] = new Array(obj.Accelleration.factor);

不幸的是,当我这样做时,单位[0] [0]会提出同样的事情;

"Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)"

我怎样才能使它像数组一样工作?谢谢!

1 个答案:

答案 0 :(得分:0)

您在JSON中拥有的是一个包含字符串表示的字符串。由于该表示不是JSON,因此您无法直接解析它(但您可以通过在其周围添加括号将其转换为JSON)。

不要使用包含字符串的字符串,而是使其成为包含字符串的数组。然后当你解析它时,你已经拥有了数组:

var text = '{"Accelleration": { '+
  '"unit": ["Meter/sq.sec (m/sec^2)", "Foot/sq.sec (ft/sec^2)", "G (g)", "Galileo (gal)", "Inch/sq.sec (in/sec^2)" ], '+
  '"factor": [ 1, .3048, 9.806650, .01, 2.54E-02 ]'+
  '}}'
var obj = JSON.parse(text);

现在你拥有了你的数组,而不必做任何事情,只需从对象中获取它们:

unit[0] = obj.Accelleration.unit;
factor[0] = obj.Accelleration.factor;