How to convert an input of type string into type object array in node js










0















I am creating a cli app & I get an input from the user : print [name:'joe', age:19] where arg = [name:'joe', age:19]



But when I do typeof arg, it returns string. I tried using json.parse [throws error], slice(1,-1) [removes outer array brackets & type remains string] and Array.from(arg) [splits all the brackets & letters into different elements].



So how do I convert [name:'joe', age:19] into type object array?



Code Snippet :



vorpal
.command('input <array>')
.action(function(args,cb)
let array = args.array;
this.log(array); //returns [name:'joe',age:19]
this.log(typeof array); //returns string
cb();


);










share|improve this question
























  • please, paste your code.

    – lependu
    Nov 14 '18 at 9:39











  • Does this post answer your question? stackoverflow.com/questions/4351521/…

    – Sjoerd
    Nov 14 '18 at 9:42











  • @Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

    – Endemic
    Nov 14 '18 at 9:46











  • what is the error when you use JSON.parse?

    – Yong Quan
    Nov 14 '18 at 9:48











  • @YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

    – Endemic
    Nov 14 '18 at 9:51















0















I am creating a cli app & I get an input from the user : print [name:'joe', age:19] where arg = [name:'joe', age:19]



But when I do typeof arg, it returns string. I tried using json.parse [throws error], slice(1,-1) [removes outer array brackets & type remains string] and Array.from(arg) [splits all the brackets & letters into different elements].



So how do I convert [name:'joe', age:19] into type object array?



Code Snippet :



vorpal
.command('input <array>')
.action(function(args,cb)
let array = args.array;
this.log(array); //returns [name:'joe',age:19]
this.log(typeof array); //returns string
cb();


);










share|improve this question
























  • please, paste your code.

    – lependu
    Nov 14 '18 at 9:39











  • Does this post answer your question? stackoverflow.com/questions/4351521/…

    – Sjoerd
    Nov 14 '18 at 9:42











  • @Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

    – Endemic
    Nov 14 '18 at 9:46











  • what is the error when you use JSON.parse?

    – Yong Quan
    Nov 14 '18 at 9:48











  • @YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

    – Endemic
    Nov 14 '18 at 9:51













0












0








0








I am creating a cli app & I get an input from the user : print [name:'joe', age:19] where arg = [name:'joe', age:19]



But when I do typeof arg, it returns string. I tried using json.parse [throws error], slice(1,-1) [removes outer array brackets & type remains string] and Array.from(arg) [splits all the brackets & letters into different elements].



So how do I convert [name:'joe', age:19] into type object array?



Code Snippet :



vorpal
.command('input <array>')
.action(function(args,cb)
let array = args.array;
this.log(array); //returns [name:'joe',age:19]
this.log(typeof array); //returns string
cb();


);










share|improve this question
















I am creating a cli app & I get an input from the user : print [name:'joe', age:19] where arg = [name:'joe', age:19]



But when I do typeof arg, it returns string. I tried using json.parse [throws error], slice(1,-1) [removes outer array brackets & type remains string] and Array.from(arg) [splits all the brackets & letters into different elements].



So how do I convert [name:'joe', age:19] into type object array?



Code Snippet :



vorpal
.command('input <array>')
.action(function(args,cb)
let array = args.array;
this.log(array); //returns [name:'joe',age:19]
this.log(typeof array); //returns string
cb();


);







javascript node.js vorpal.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 9:45







Endemic

















asked Nov 14 '18 at 9:37









EndemicEndemic

318




318












  • please, paste your code.

    – lependu
    Nov 14 '18 at 9:39











  • Does this post answer your question? stackoverflow.com/questions/4351521/…

    – Sjoerd
    Nov 14 '18 at 9:42











  • @Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

    – Endemic
    Nov 14 '18 at 9:46











  • what is the error when you use JSON.parse?

    – Yong Quan
    Nov 14 '18 at 9:48











  • @YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

    – Endemic
    Nov 14 '18 at 9:51

















  • please, paste your code.

    – lependu
    Nov 14 '18 at 9:39











  • Does this post answer your question? stackoverflow.com/questions/4351521/…

    – Sjoerd
    Nov 14 '18 at 9:42











  • @Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

    – Endemic
    Nov 14 '18 at 9:46











  • what is the error when you use JSON.parse?

    – Yong Quan
    Nov 14 '18 at 9:48











  • @YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

    – Endemic
    Nov 14 '18 at 9:51
















please, paste your code.

– lependu
Nov 14 '18 at 9:39





please, paste your code.

– lependu
Nov 14 '18 at 9:39













Does this post answer your question? stackoverflow.com/questions/4351521/…

– Sjoerd
Nov 14 '18 at 9:42





Does this post answer your question? stackoverflow.com/questions/4351521/…

– Sjoerd
Nov 14 '18 at 9:42













@Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

– Endemic
Nov 14 '18 at 9:46





@Sjoerd that should not be a problem because I am using a library called vorpal js to accept arguments but it always returns the argument as a string.

– Endemic
Nov 14 '18 at 9:46













what is the error when you use JSON.parse?

– Yong Quan
Nov 14 '18 at 9:48





what is the error when you use JSON.parse?

– Yong Quan
Nov 14 '18 at 9:48













@YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

– Endemic
Nov 14 '18 at 9:51





@YongQuan I get : SyntaxError: Unexpected token n in JSON at position 2

– Endemic
Nov 14 '18 at 9:51












4 Answers
4






active

oldest

votes


















0














JSON.parse expects keys to be in double quotes. so somehow you have to change the input to this format



JSON.parse(["name":"joe", "age":"19"])


and the output would be



enter image description here






share|improve this answer























  • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:01


















0














The input that you pass is not a valid JSON structure that's why JSON.parse has shown parsing error.



var validInput = '["name":"joe","age":19]';
console.log(JSON.parse(validInput));





share|improve this answer

























  • you probably meant var validInput = '["name":"joe","age":19]';?

    – Kaddath
    Nov 14 '18 at 10:00











  • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:02











  • @Endemic You have to write your custom logic then to parse this string and create an valid json.

    – front_end_dev
    Nov 14 '18 at 10:05











  • @Kaddath yes. Sorry i miss the quotes '. Edit answer

    – front_end_dev
    Nov 14 '18 at 10:05












  • you need double quotes for "joe" too ;)

    – Kaddath
    Nov 14 '18 at 10:13


















0














Run Code Snippet.






var obj = new Object(name:'joe', age:19);
console.log(typeof obj);








share|improve this answer

























  • When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

    – Endemic
    Nov 14 '18 at 10:08


















0














You can still try these regexes, that will convert your string into valid JSON. Be careful that it's not perfect, this version only accepts letters and numbers as keys for objects, while other characters can be valid too for object keys. You have to modify this part [a-zA-Z0-9] to improve it if you know a bit of regex..






var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
console.log('original string: ', str);

validJson = str.replace(/(s*)/g, '$1"$2"$3');
console.log('modified string: ', validJson);

obj = JSON.parse(validJson);
console.log('decoded from JSON: ', obj);





EDIT: regex updated to support object keys defined with simple quotes (2nd object). NOTE: it keeps already well formatted JSON as it is (3rd object).






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53297013%2fhow-to-convert-an-input-of-type-string-into-type-object-array-in-node-js%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    JSON.parse expects keys to be in double quotes. so somehow you have to change the input to this format



    JSON.parse(["name":"joe", "age":"19"])


    and the output would be



    enter image description here






    share|improve this answer























    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:01















    0














    JSON.parse expects keys to be in double quotes. so somehow you have to change the input to this format



    JSON.parse(["name":"joe", "age":"19"])


    and the output would be



    enter image description here






    share|improve this answer























    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:01













    0












    0








    0







    JSON.parse expects keys to be in double quotes. so somehow you have to change the input to this format



    JSON.parse(["name":"joe", "age":"19"])


    and the output would be



    enter image description here






    share|improve this answer













    JSON.parse expects keys to be in double quotes. so somehow you have to change the input to this format



    JSON.parse(["name":"joe", "age":"19"])


    and the output would be



    enter image description here







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 14 '18 at 9:58









    Asim KhanAsim Khan

    38719




    38719












    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:01

















    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:01
















    So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:01





    So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:01













    0














    The input that you pass is not a valid JSON structure that's why JSON.parse has shown parsing error.



    var validInput = '["name":"joe","age":19]';
    console.log(JSON.parse(validInput));





    share|improve this answer

























    • you probably meant var validInput = '["name":"joe","age":19]';?

      – Kaddath
      Nov 14 '18 at 10:00











    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:02











    • @Endemic You have to write your custom logic then to parse this string and create an valid json.

      – front_end_dev
      Nov 14 '18 at 10:05











    • @Kaddath yes. Sorry i miss the quotes '. Edit answer

      – front_end_dev
      Nov 14 '18 at 10:05












    • you need double quotes for "joe" too ;)

      – Kaddath
      Nov 14 '18 at 10:13















    0














    The input that you pass is not a valid JSON structure that's why JSON.parse has shown parsing error.



    var validInput = '["name":"joe","age":19]';
    console.log(JSON.parse(validInput));





    share|improve this answer

























    • you probably meant var validInput = '["name":"joe","age":19]';?

      – Kaddath
      Nov 14 '18 at 10:00











    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:02











    • @Endemic You have to write your custom logic then to parse this string and create an valid json.

      – front_end_dev
      Nov 14 '18 at 10:05











    • @Kaddath yes. Sorry i miss the quotes '. Edit answer

      – front_end_dev
      Nov 14 '18 at 10:05












    • you need double quotes for "joe" too ;)

      – Kaddath
      Nov 14 '18 at 10:13













    0












    0








    0







    The input that you pass is not a valid JSON structure that's why JSON.parse has shown parsing error.



    var validInput = '["name":"joe","age":19]';
    console.log(JSON.parse(validInput));





    share|improve this answer















    The input that you pass is not a valid JSON structure that's why JSON.parse has shown parsing error.



    var validInput = '["name":"joe","age":19]';
    console.log(JSON.parse(validInput));






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 14 '18 at 10:20

























    answered Nov 14 '18 at 9:54









    front_end_devfront_end_dev

    1,3501511




    1,3501511












    • you probably meant var validInput = '["name":"joe","age":19]';?

      – Kaddath
      Nov 14 '18 at 10:00











    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:02











    • @Endemic You have to write your custom logic then to parse this string and create an valid json.

      – front_end_dev
      Nov 14 '18 at 10:05











    • @Kaddath yes. Sorry i miss the quotes '. Edit answer

      – front_end_dev
      Nov 14 '18 at 10:05












    • you need double quotes for "joe" too ;)

      – Kaddath
      Nov 14 '18 at 10:13

















    • you probably meant var validInput = '["name":"joe","age":19]';?

      – Kaddath
      Nov 14 '18 at 10:00











    • So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

      – Endemic
      Nov 14 '18 at 10:02











    • @Endemic You have to write your custom logic then to parse this string and create an valid json.

      – front_end_dev
      Nov 14 '18 at 10:05











    • @Kaddath yes. Sorry i miss the quotes '. Edit answer

      – front_end_dev
      Nov 14 '18 at 10:05












    • you need double quotes for "joe" too ;)

      – Kaddath
      Nov 14 '18 at 10:13
















    you probably meant var validInput = '["name":"joe","age":19]';?

    – Kaddath
    Nov 14 '18 at 10:00





    you probably meant var validInput = '["name":"joe","age":19]';?

    – Kaddath
    Nov 14 '18 at 10:00













    So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:02





    So should I force the user to follow the json syntax while passing input? Isnt there a way to convert the input type to [object Array] directly?

    – Endemic
    Nov 14 '18 at 10:02













    @Endemic You have to write your custom logic then to parse this string and create an valid json.

    – front_end_dev
    Nov 14 '18 at 10:05





    @Endemic You have to write your custom logic then to parse this string and create an valid json.

    – front_end_dev
    Nov 14 '18 at 10:05













    @Kaddath yes. Sorry i miss the quotes '. Edit answer

    – front_end_dev
    Nov 14 '18 at 10:05






    @Kaddath yes. Sorry i miss the quotes '. Edit answer

    – front_end_dev
    Nov 14 '18 at 10:05














    you need double quotes for "joe" too ;)

    – Kaddath
    Nov 14 '18 at 10:13





    you need double quotes for "joe" too ;)

    – Kaddath
    Nov 14 '18 at 10:13











    0














    Run Code Snippet.






    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);








    share|improve this answer

























    • When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

      – Endemic
      Nov 14 '18 at 10:08















    0














    Run Code Snippet.






    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);








    share|improve this answer

























    • When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

      – Endemic
      Nov 14 '18 at 10:08













    0












    0








    0







    Run Code Snippet.






    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);








    share|improve this answer















    Run Code Snippet.






    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);








    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);





    var obj = new Object(name:'joe', age:19);
    console.log(typeof obj);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 14 '18 at 10:40

























    answered Nov 14 '18 at 9:55









    Olayinka OOlayinka O

    623320




    623320












    • When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

      – Endemic
      Nov 14 '18 at 10:08

















    • When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

      – Endemic
      Nov 14 '18 at 10:08
















    When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

    – Endemic
    Nov 14 '18 at 10:08





    When I follow your method, the type changes to object but when I console.log(obj) it returns the output - [String: '[name:'arjun',age:19]']

    – Endemic
    Nov 14 '18 at 10:08











    0














    You can still try these regexes, that will convert your string into valid JSON. Be careful that it's not perfect, this version only accepts letters and numbers as keys for objects, while other characters can be valid too for object keys. You have to modify this part [a-zA-Z0-9] to improve it if you know a bit of regex..






    var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
    console.log('original string: ', str);

    validJson = str.replace(/(s*)/g, '$1"$2"$3');
    console.log('modified string: ', validJson);

    obj = JSON.parse(validJson);
    console.log('decoded from JSON: ', obj);





    EDIT: regex updated to support object keys defined with simple quotes (2nd object). NOTE: it keeps already well formatted JSON as it is (3rd object).






    share|improve this answer





























      0














      You can still try these regexes, that will convert your string into valid JSON. Be careful that it's not perfect, this version only accepts letters and numbers as keys for objects, while other characters can be valid too for object keys. You have to modify this part [a-zA-Z0-9] to improve it if you know a bit of regex..






      var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
      console.log('original string: ', str);

      validJson = str.replace(/(s*)/g, '$1"$2"$3');
      console.log('modified string: ', validJson);

      obj = JSON.parse(validJson);
      console.log('decoded from JSON: ', obj);





      EDIT: regex updated to support object keys defined with simple quotes (2nd object). NOTE: it keeps already well formatted JSON as it is (3rd object).






      share|improve this answer



























        0












        0








        0







        You can still try these regexes, that will convert your string into valid JSON. Be careful that it's not perfect, this version only accepts letters and numbers as keys for objects, while other characters can be valid too for object keys. You have to modify this part [a-zA-Z0-9] to improve it if you know a bit of regex..






        var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
        console.log('original string: ', str);

        validJson = str.replace(/(s*)/g, '$1"$2"$3');
        console.log('modified string: ', validJson);

        obj = JSON.parse(validJson);
        console.log('decoded from JSON: ', obj);





        EDIT: regex updated to support object keys defined with simple quotes (2nd object). NOTE: it keeps already well formatted JSON as it is (3rd object).






        share|improve this answer















        You can still try these regexes, that will convert your string into valid JSON. Be careful that it's not perfect, this version only accepts letters and numbers as keys for objects, while other characters can be valid too for object keys. You have to modify this part [a-zA-Z0-9] to improve it if you know a bit of regex..






        var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
        console.log('original string: ', str);

        validJson = str.replace(/(s*)/g, '$1"$2"$3');
        console.log('modified string: ', validJson);

        obj = JSON.parse(validJson);
        console.log('decoded from JSON: ', obj);





        EDIT: regex updated to support object keys defined with simple quotes (2nd object). NOTE: it keeps already well formatted JSON as it is (3rd object).






        var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
        console.log('original string: ', str);

        validJson = str.replace(/(s*)/g, '$1"$2"$3');
        console.log('modified string: ', validJson);

        obj = JSON.parse(validJson);
        console.log('decoded from JSON: ', obj);





        var str = "[name:'joe', age:19, 'name':'jack', age:21, "name":"jane", age:23]", validJson, obj;
        console.log('original string: ', str);

        validJson = str.replace(/(s*)/g, '$1"$2"$3');
        console.log('modified string: ', validJson);

        obj = JSON.parse(validJson);
        console.log('decoded from JSON: ', obj);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 11:58

























        answered Nov 14 '18 at 11:01









        KaddathKaddath

        2,8991517




        2,8991517



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53297013%2fhow-to-convert-an-input-of-type-string-into-type-object-array-in-node-js%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo