3

I want to dump this array to string and get the same object after evaluating it.

arr = [5, 86, function() { console.log(arguments); }, [console.log, 357]];

Although, functions may have extra properties, only the code is necessary to reproduce.

I can't find a way to do this in Node:

> console.log(arr)
[5, 86, [Function] [ [Function], 357] ]

> util.format('%j', arr)
'[5,86,null,[null,357]]'

> arr.toString()
'5,86,function () { console.log(arguments); },function () {\n  process.stdout.write(util.format.apply(this, arguments) + \'\\n\');\n},357'

The latter has flatterned the array.

Is there a better way?

update: found the satisfying solution, see my own answer.

5 Answers 5

2

JSON can't represent functions. There's no way to put your array in JSON. People often use the term "JSON" to mean any Javascript object literal. It isn't: it's a strictly defined data format.

UPDATE: The OP has removed "JSON" from the title.

Sign up to request clarification or add additional context in comments.

2 Comments

I've changed the question title. :)
I thought it could represent functions. Or is it BSON that can? Because i used to store a function in MongoDB
0

as functions aren't a recognized JSON datatype you'll have to stringify them. here's an example from the wild: https://github.com/mikeal/node.couchapp.js/blob/master/main.js#L122

Comments

0

If I have you right, you want to flatten it to a string, while retaining the original then convert it back to an array?

var original = ['a','b','c'];
var str = original.toString();
var newAgain = str.split(',');

console.log(original); //['a','b','c']
console.log(str);// "a,b,c"
console.log(newAgain); //['a','b','c']

Comments

0

I found what satisfies me: jsDump

Comments

0

https://github.com/Benvie/JASON

It won't have all the context necessary when code is inaccessible to you, but it will at least not throw reference errors when evaled.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.