× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

String to array nodejs

Mehran Hatami
May 02, 2015
<p>Firstly, what you have as your object model is more of a hash like object or simply a JavaScript object with keys and values, so the best way to do that is simply using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="nofollow">JSON.parse</a>.</p> <p>So if you can do it as you said: I can format the string in any way, you better first change your formatting to have something like:</p> <pre><code>'{"id1":234,"id2":4566,"id3":3000}' </code></pre> <p>instead of :</p> <pre><code>id1:234,id2:4566,id3:3000 </code></pre> <p>you can do it using <code>JSON.stringify</code> on the client side JavaScript using a JavaScript object without you needing to deal with string formatting:</p> <pre><code>//on the client side var myObj = {}; myObj.id1 = 234; myObj.id2 = 4566; myObj.id3 = 3000; var objStr = JSON.stringify(myObj); </code></pre> <p>let's say you encrypt your string using a function named <code>encrypt</code>:</p> <pre><code>var encryptedStr = encrypt(objStr); //so now you should use encodeURI to be able to put it in the queryString var queryStringParam = encodeURI(encryptedStr); </code></pre> <p>now you put the <code>queryStringParam</code> in the queryString.</p> <p>Then on the node.js side, all you should do is parsing it as a JSON object. The other important point that you probably have considered doing it is using <code>decodeURI</code>. For the last step, let's say you are using e function named <code>decrypt</code>:</p> <pre><code>//the server-side code var decryptedStr = decrypt(decodeURI(yourQueryString)); var obj = JSON.parse(decryptedStr); </code></pre> <p>Now obj is exactly what you want.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23741767/String%20to%20array%20nodejs/23742073">Stack Overflow</a>.</p>
comments powered by Disqus