I developed NodeJS program that can read and write to WordPress Rest API. I’m having problem of reading or writing properly the data in NodeJS and WordPress and vice versa.
NodeJS Writes JSON Objects to WordPress Rest API
Any JSON String[] or Object[], will be saved into serialized PHP string by WordPress.
Surprisingly, when NodeJS read the data save in serialize string, NodeJS can read it as JSON object without needs to call JSON.parse().
However JSON Object, will be saved as string by WordPress but still follows JSON string format.
As the JSON Object is saved as string, when NodeJS read the data via WordPress Rest API, NodeJS has to call JSON.parse() to convert it back into JSON Object.
Examples of JSON Object saved by WordPress Rest API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
NodeJS JSON String[]: [ '019-3312 493' ] Saved in Wordress PHP MySQL as PHP Serialize string: a:1:{i:0;s:12:"019-3312 493";} NodeJS JSON Object[]: [ { day: 'monday', open: '8:00 AM', close: '10:00 PM' }, { day: 'tuesday', open: '8:00 AM', close: '10:00 PM' }, { day: 'wednesday', open: '8:00 AM', close: '10:00 PM' }, { day: 'thursday', open: '8:00 AM', close: '10:00 PM' }, { day: 'friday', open: '8:00 AM', close: '10:00 PM' }, { day: 'saturday', open: '8:00 AM', close: '10:00 PM' }, { day: 'sunday', open: '8:00 AM', close: '10:00 PM' } ] Saved as string that follows JSON Object format in Wordpress PHP MySQL a:7:{i:0;a:3:{s:3:"day";s:6:"monday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:1;a:3:{s:3:"day";s:7:"tuesday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:2;a:3:{s:3:"day";s:9:"wednesday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:3;a:3:{s:3:"day";s:8:"thursday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:4;a:3:{s:3:"day";s:6:"friday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:5;a:3:{s:3:"day";s:8:"saturday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}i:6;a:3:{s:3:"day";s:6:"sunday";s:4:"open";s:7:"8:00 AM";s:5:"close";s:8:"10:00 PM";}} NodeJS JSON Object: { open24h: true, hasbreakfast: true, hasdrivethru: false, delivery: true, selfcollect: true, haswifi: true } Saved as string that follows JSON Object format in Wordpress PHP MySQL {"open24h":true,"hasbreakfast":true,"hasdrivethru":false,"delivery":true,"selfcollect":true,"haswifi":true} |
How To Have Consistency?
By having JSON arrays save as PHP serialize string and JSON object as string in PHP, I need to have do extra checking or conversion by calling JSON.parse()
Another possible solution is to call JSON.stringify() to JSON arrays so it is saved as string at PHP. However, it is still extra step that we need to do and it doesn’t solve the problem stated above where there is no consistency.
So, in short there is no possible solution to have consistency, we still need to do extra step as mentioned above.