使用node.js将多维数组转换为JSON

时间:2022-10-22 23:02:15

I'm getting a BIG multidimensional array after combining few simple arrays, now I need to convert it in a JSON string right before sending it to Mongodb. Here is the array structure:

在组合了几个简单的数组后,我得到了一个BIG多维数组,现在我需要在将它发送到Mongodb之前将其转换为JSON字符串。这是数组结构:

[ '0',
  [ [ 'id', 1 ],
    [ 'country', 0 ],
    [ 'people', 3 ],
    [ 'name', 'WELLINGTON ALFRED' ],
    [ 'location', 'hill' ],
    [ 'filename', 243245.PDF]]]

What's the best practice to do it in Node.js? Thank's in advance!

在Node.js中执行此操作的最佳做​​法是什么?提前致谢!

1 个解决方案

#1


1  

you totally can use JSON.stringify

你完全可以使用JSON.stringify

string_for_mongo = JSON.stringify(your_array)

string_for_mongo = JSON.stringify(your_array)

but you also can use any of these drivers for mongodb

但你也可以使用任何这些驱动程序的mongodb

if you want to convert these arrays to object you can just use something like this

如果你想将这些数组转换为对象,你可以使用这样的东西

pairs = {}
for ( pair in your_array[1] ) { pairs[your_array[1][pair][0]] = your_array[1][pair][1] }
objekt = {}
objekt[your_array[0]] = pairs

I think there is no better solution than not to use such an arrays. Try to form data in objects from the beginning.

我认为没有比不使用这样的阵列更好的解决方案了。尝试从头开始在对象中形成数据。

#1


1  

you totally can use JSON.stringify

你完全可以使用JSON.stringify

string_for_mongo = JSON.stringify(your_array)

string_for_mongo = JSON.stringify(your_array)

but you also can use any of these drivers for mongodb

但你也可以使用任何这些驱动程序的mongodb

if you want to convert these arrays to object you can just use something like this

如果你想将这些数组转换为对象,你可以使用这样的东西

pairs = {}
for ( pair in your_array[1] ) { pairs[your_array[1][pair][0]] = your_array[1][pair][1] }
objekt = {}
objekt[your_array[0]] = pairs

I think there is no better solution than not to use such an arrays. Try to form data in objects from the beginning.

我认为没有比不使用这样的阵列更好的解决方案了。尝试从头开始在对象中形成数据。