问题
I am trying to get a JSON object and so to make sure I had it I wrote the code like this:
var payload = JSON.parse(
JSON.stringify(Buffer.from(pubsubMessage.data, 'base64').toString())
);
console.log(payload);
// { timestamp: '1533564208', device_id: '2nd_test', temperature: '20.0' }
console.log(typeof payload);
// string
EDIT - Based on your feedback, I will elaborate further on the code and the type. Below is the full code and what it returns:
var payload = Buffer.from(pubsubMessage.data, 'base64').toString();
console.log('payload 0');
console.log(payload);
// { timestamp: "1533564208", device_id: "2nd_test", temperature: "20.0" }
console.log(typeof payload);
//string
var payload2 = JSON.parse(
Buffer.from(pubsubMessage.data, 'base64').toString()
);
console.log('payload 2');
console.log(payload2);
// SyntaxError: Unexpected token t in JSON at position 2 at JSON.parse
EDIT 2 - To better understand the context I am using the Functions from GCloud with the PubSub trigger. So the data in the buffer is coming from pubsub.
I don't understand why the function JSON.parse crashes though it is obviously a JSON format in a string.
Any clue on this?
Thanks!
回答1:
This happened because you "stringified" twice your data, with .toString()
and with JSON.stringify
// since I dont have your data, I will use this as example
var example = { a : 'a', b : 'b' };
var payload = JSON.parse(JSON.stringify(example.toString()));
// will log [object Object]
console.log(payload);
// will log string
console.log(typeof payload);
So, when you desserialize using JSON.parse
, it still remains as string. You only need to serialize once:
var example = { a : 'a', b : 'b' };
var payload = JSON.parse(JSON.stringify(example));
// will log the object correctly
console.log(payload);
// will log object
console.log(typeof payload);
回答2:
The issue was sort of confusing. Hardcoded in the code the 2 below versions would give me the same result and work fine.
payload= { timestamp: "1533564208", device_id: "2nd_test", temperature: "20.0" }
and
payload='{"timestamp":"1533564208","device_id":"2nd_test","temperature":"20.0"}'
But when using the PubSub Gcloud and the Buffer function, I had to make sure to pass in
payload='{"timestamp":"1533564208","device_id":"2nd_test","temperature":"20.0"}'
and not
payload= { timestamp: "1533564208", device_id: "2nd_test", temperature: "20.0" }
otherwise it would not consider it as valid JSON.
回答3:
Why do you do this ?
var payload2 = JSON.parse(
Buffer.from(pubsubMessage.data, 'base64').toString()
);
You could just print the result of Buffer.from(pubsubMessage.data, 'base64').toString()
来源:https://stackoverflow.com/questions/51953504/issue-with-getting-a-json-object-to-work-in-nodejs