0

I have a textarea with an id of 'dataArrayField' which has code in it, example:

item1: {
    type: 'foo',
    fieldName: 'bar'}
},
item2: {
    type: 'cat',
    fieldName: 'dog'
}

I then run var content = $('#dataArrayField').serialize(); on this textarea, which has a nem of codeformat, so the returned data would be something like:

codeFormat=item1%3a+ etc etc

I then use the $.deparam(content) Javascript plugin to turn the serialized string to an object.

This works, however, the only key that actually is returned, is the codeFormat name, then the value is the text in the field above, so I get something like this:

enter image description here

What can I do so that I can access all the information in the passed object!

4
  • 1
    Is #dataArrayField your textarea or form? Commented Jun 18, 2014 at 2:53
  • @ShannonHochkins I don't think so, you can serialize a form but not a textarea, just take a look at your html Commented Jun 18, 2014 at 3:03
  • You can definitely serialize a textarea..... @OscarJara, its working, and that's what I'm doing? Commented Jun 18, 2014 at 3:20
  • @OscarJara, api.jquery.com/serialize, you can definitely serialize textareas. Commented Jun 18, 2014 at 3:34

3 Answers 3

2

If you have a string which represents a javascript object and want to create an actual object from that, one option would be to use eval.

var str = "item1: {type: 'foo',fieldName: 'bar'},item2: {type: 'cat',fieldName: 'dog'}";
var obj = eval('({' + str + '})');
alert(obj.item1.type); // foo!

If a user can enter text that is later displayed to other users, this is probably not a very secure thing to do.

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

1 Comment

It would be safer to use JSON.parse()
1

You can either put a valid JSON string in the textarea such as

{"item1":{"type":"foo","fieldName":"bar"},"item2":{"type":"cat","fieldName":"dog"}}

or you can use regular expressions as in THIS WORKING DEMO to clean it up before applying JSON.parse(). As @jibsales has already pointed out, do not use eval():

$(function() {
    var val = $('#dataArrayField').val().replace(/[\s']/g,'').replace(/(\w+)/g,'"$1"');
    val = '{' + val.replace(/\}\},/g,'},') + '}';
    console.log( JSON.parse(val) );
});

1 Comment

I Changed this to the accepted answer as everyone is saying do not use eval.
1

Eval is evil. Consider using JSON.serialize() and JSON.parse() instead. The objects entered in the text area will have to be valid JSON but it is much more secure.

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.