简体   繁体   中英

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. 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:

./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>"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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