Issue With Getting A Json Object To Work In Nodejs
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').toStrin
Solution 1:
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.
Solution 2:
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 examplevar example = { a : 'a', b : 'b' };
var payload = JSON.parse(JSON.stringify(example.toString()));
// will log [object Object]console.log(payload);
// will log stringconsole.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 correctlyconsole.log(payload);
// will log objectconsole.log(typeof payload);
Solution 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()
Post a Comment for "Issue With Getting A Json Object To Work In Nodejs"