0

In order to satisfy a JQuery autocomplete I have, right now, used this initialization code:

var KdNameTags = [{label:"...", idx:0},{label:"...", idx:1},{...}]

This works well, and it initializes an array of objects, each one containing a property "label" and "idx", like demanded by autocomplete. See details in the JQuery docs if required. Now, I want the definition delivered via a string variable, like:

var strTags = '{label:"...", idx:0},{label:"...", idx:1},{...}';

but I can't figure out how I need to proceed, and I have Javascript creating the array of objects from that string.

var KdNameTags = [strTags] 

it does not do the trick, of course...

1
  • Your string not in proper json format, so you won't be able to parse it using JSON.parse().... will you be able to fix the code that is generating the string Commented Jul 9, 2015 at 13:45

3 Answers 3

2

var strTags = '{"label":"...", "idx":0},{"label":"...", "idx":1}';
var arr = JSON.parse("[" + strTags + "]");
console.log(arr);
$("pre").text(JSON.stringify(arr, null, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre></pre>

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

1 Comment

Thanks, this worked like a charm. First hint was to bring the init string into JSON format (put "" around the member names), and then shove the string into a JSON parser, I prefer to use jQuery.parseJSON(strTags); but your code has showed me the way. Excellent!
2

You can add "[]" to the string variable and then use eval(), to create your array of objects.

var strTags = '[{label:"...", idx:0},{label:"...", idx:1}]';
var yourObject = eval(strTags)

2 Comments

It's really nice method, +1 added
Would have worked too, I guess, but I preferred to go the JSON parser idea. Thanks though!
0

You can do something like this , with the help of replace() and JSON.parse()

var strTags = '{label:"...", idx:0},{label:"...", idx:1}';

var json = JSON.parse('[' + strTags.replace(/({|,)\s*(\w+)\s*:/g, '$1"$2":') + ']');

console.log(json);

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.