简体   繁体   中英

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

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();

});

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)); 

Run Code Snippet.

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

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

在此处输入图片说明

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*|,\\s*)'?([a-zA-Z0-9]+)'?(\\s*:)/g, '$1"$2"$3').replace(/(:\\s*)'(.*?)'(\\s*,|\\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).

One solution is to use eval , eg

> eval("[{name:'joe', age:19}]")
[ { name: 'joe', age: 19 } ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM