Skip to content

Instantly share code, notes, and snippets.

@dsk52
Forked from shoota/jsontest.js
Created December 15, 2015 08:20
Show Gist options
  • Save dsk52/70fd6b34c16903bd9c00 to your computer and use it in GitHub Desktop.
Save dsk52/70fd6b34c16903bd9c00 to your computer and use it in GitHub Desktop.
node.jsでstringとObjectの相互置換の書き方 # 「オブジェクト -> 文字列」では、関数オブジェクトが表示されない。 # 「文字列 -> オブジェクト」では、外側のブレース括弧も必要で、stringの書き方に注意する。 要するにJSONの仕様に厳密な表現しか受け付けない(っぽい)。そもそもデータコンテナフォーマットですし。
// 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