Last active
December 24, 2015 06:48
-
-
Save shoota/6759158 to your computer and use it in GitHub Desktop.
node.jsでstringとObjectの相互置換の書き方 # 「オブジェクト -> 文字列」では、関数オブジェクトが表示されない。
# 「文字列 -> オブジェクト」では、外側のブレース括弧も必要で、stringの書き方に注意する。 要するにJSONの仕様に厳密な表現しか受け付けない(っぽい)。そもそもデータコンテナフォーマットですし。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// execute at node.js v.0.10.19 | |
/*---------------------------------------------------------------*/ | |
var toStrObj={}; | |
toStrObj.name = "shoota"; | |
toStrObj.age = 29; | |
toStrObj.body = {locale:'Japan',sex:'m',hasChildren:true}; | |
toStrObj.talk = function(){console.log('hello');}; | |
var toStr = JSON.stringify(toStrObj); | |
console.log(toStr); | |
console.log('--------------------------------------------------------------'); | |
/*---------------------------------------------------------------*/ | |
// required outer brace, e.g '{}'. | |
//var toObjString = '"name":"shuta","age":29,"body":{"locale":"America","sex":"m","hasChildren":false}'; | |
var toObjString = '{"name":"shuta","age":29,"body":{"locale":"America","sex":"m","hasChildren":false}}'; | |
var toObj = JSON.parse(toObjString); | |
var s = toObj.body.sex === 'm' ? 'He ' : 'She '; | |
var sentence = toObj.body.hasChildren ? 'has' : 'do not have'; | |
console.log(toObj.name + " is " +toObj.age+" years old."); | |
console.log(s + sentence + ' any children.'); | |
/* | |
[console] | |
% node jsontest.js | |
{"name":"shoota","age":29,"body":{"locale":"Japan","sex":"m","hasChildren":true}} | |
-------------------------------------------------------------- | |
shuta is 29 years old. | |
He do not have any children. | |
Process finished with exit code 0 | |
*/ | |
var re = JSON.parse(JSON.stringify(toStrObj)); | |
re.talk(); | |
// TypeError: Object #<Object> has no method 'talk' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment