source

JSON 개체를 버퍼로 변환하고 버퍼를 JSON 개체로 변환

ittop 2023. 3. 18. 09:23
반응형

JSON 개체를 버퍼로 변환하고 버퍼를 JSON 개체로 변환

JSON 오브젝트를 가지고 있으며, 그것을 변환하고 있습니다.Buffer여기서 몇 가지 작업을 하고 있습니다.나중에 같은 버퍼 데이터를 변환하여 유효한 JSON 개체로 변환합니다.

Node V6.9.1에서 작업 중입니다.

아래는 내가 시도했지만, 나는 얻는 코드이다.[object object]JSON으로 다시 변환하여 이 오브젝트를 다시 JSON으로 변환할 수 없습니다.

var obj = {
   key:'value',
   key:'value',
   key:'value',
   key:'value',
   key:'value'
}

var buf = new Buffer.from(obj.toString());

console.log('Real Buffer ' + buf);  //This prints --> Real Buffer <Buffer 5b 6f 62 6a 65 63 74>

var temp = buf.toString();

console.log('Buffer to String ' + buf);  //This prints --> Buffer to String [object Object]

그래서 나는 검사 방법을 사용하여 전체 객체를 인쇄하려고 했다.

console.log('Full temp ' + require('util').inspect(buf, { depth: null }));  //This prints --> '[object object]' [not printing the obj like declared above]

배열처럼 읽으려고 하면

 console.log(buf[0]);  // This prints --> [ 

파싱도 해봤는데 던지네요.SyntaxError: Unexpected token o in JSON at position 2

내가 작성한 (즉, 위에서 선언한) 실제 객체로 볼 필요가 있습니다.

제발 도와주세요..

호출이 아닌 json 문자열을 지정해야 합니다.toString

var buf = Buffer.from(JSON.stringify(obj));

문자열을 json obj로 변환하는 경우:

var temp = JSON.parse(buf.toString());

여기에 이미지 설명 입력

아래 스니펫을 복사해 주세요.

const jsonObject = {
        "Name":'Ram',
        "Age":'28',
        "Dept":'IT'
      }
      const encodedJsonObject = Buffer.from(JSON.stringify(jsonObject)).toString('base64'); 
      console.log('--encodedJsonObject-->', encodedJsonObject)
      //Output     --encodedJsonObject--> eyJOYW1lIjoiUmFtIiwiQWdlIjoiMjgiLCJEZXB0IjoiSVQifQ==

      const decodedJsonObject = Buffer.from(encodedJsonObject, 'base64').toString('ascii'); 
      console.log('--decodedJsonObject-->', JSON.parse(decodedJsonObject))
      //Output     --decodedJsonObject--> {Name: 'Ram', Age: '28', Dept: 'IT'}

@Ebrahim으로 먼저 사용해야 합니다.JSON.stringifyJSON을 문자열로 변환하고 버퍼로 변환할 수 있습니다.하지만 사용하기에 조금 위험합니다.JSON.stringify자체 참조 또는 순환 참조 시 앱이 고장날 수 있습니다.

   var y={}
   y.a=y
   JSON.stringify(y) // Uncaught TypeError: Converting circular structure to JSON

이러한 위험이 있는 경우 npm module safe-json-stringify와 같은 안전한 스트링화 솔루션을 사용하는 것이 좋습니다.

그리고 다음 작업을 수행해야 합니다.

// convert to buffer:
const stringify = require('safe-json-stringify');
var buf = Buffer.from(stringify(obj));

// convert from buffer:
var temp = JSON.parse(buf.toString());

언급URL : https://stackoverflow.com/questions/41951307/convert-a-json-object-to-buffer-and-buffer-to-json-object-back

반응형