简体   繁体   English

如何为 javascript 中的数组的键和值添加双引号

[英]How to add double quotes to both keys and values for an array in javascript

I have a an array containing buffer data as below我有一个包含缓冲区数据的数组,如下所示

 [{ Buffer_Data: <Buffer b5 eb 2d> },{ Buffer_Data: <Buffer b5 eb 2d> },{ Buffer_Data: <Buffer b5 eb 2d> },{ Buffer_Data: <Buffer b5 eb 2d> }]

I want double quotes to be added to both key and values and the result should be as below.我想将双引号添加到键和值中,结果应如下所示。

 [{ "Buffer_Data": "<Buffer b5 eb 2d>" },{ "Buffer_Data": "<Buffer b5 eb 2d>" },{ "Buffer_Data": "<Buffer b5 eb 2d>" },{ "Buffer_Data": "<Buffer b5 eb 2d>" }]

I have tried JSON.stringify but it is giving me the buffer data in invalid format.我试过 JSON.stringify 但它以无效格式提供给我缓冲区数据。 How can I convert this to array with double quotes.如何将其转换为带双引号的数组。 Please help请帮忙

Here is my code这是我的代码

 stream = fs.createReadStream('files/uploaded_files/' + req.body.fileName);
          var bufferdata = [];
        stream.on('data', async function (chunk) {
            var obj = {};
            obj.Buffer_Data =  Buffer.from(chunk.toString('binary'), 'base64');
            bufferdata.push(obj)
        });
        stream.on('end', async function(){
        var new_buffer_data = JSON.stringify(bufferdata) // This is giving invalid value
      })

Code I tried我试过的代码

    stream = fs.createReadStream('files/uploaded_files/' + req.body.fileName);
          var bufferdata = [];
        stream.on('data', async function (chunk) {
            var bytes = chunk.map(str => parseInt(str, 16));
              const buf = Buffer.from(bytes);
              var obj = {};
              obj.Buffer_Data = buf;
            buffer.push(obj)
        });
        stream.on('end', async function(){
         const stringified = JSON.stringify(buffer.map(obj => ({Buffer_Data: stringifyBuffer(obj.Buffer_Data)})));
      
        console.log(stringified);
      })

You can stringify the array of objects with Buffer data in the format that you specified using this method:您可以使用此方法以您指定的格式将包含Buffer数据的对象数组字符串化:

./so-71389714.mjs : ./so-71389714.mjs

import {Buffer} from 'buffer';

function stringifyBuffer (buf) {
  let result = '<Buffer';

  for (const byte of buf) {
    result += ` ${byte.toString(16)}`;
  }

  result += '>';
  return result;
}

const bytes = ['b5', 'eb', '2d'].map(str => parseInt(str, 16));
const buf = Buffer.from(bytes);
const obj = {Buffer_Data: buf};

// This is the array in your question
const array = [obj, obj, obj, obj];

const stringified = JSON.stringify(array.map(obj => ({Buffer_Data: stringifyBuffer(obj.Buffer_Data)})));

console.log(stringified);

$ node so-71389714.mjs
[{"Buffer_Data":"<Buffer b5 eb 2d>"},{"Buffer_Data":"<Buffer b5 eb 2d>"},{"Buffer_Data":"<Buffer b5 eb 2d>"},{"Buffer_Data":"<Buffer b5 eb 2d>"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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