jakobk
jakobk

Reputation: 1132

How can I parse this home-made string-based data format?

I need to iterate through a dataset of IDs and labels. I got some part of the code right, but I need some assistance.

// 1. String
var string = '1:answer1,2:answer2,3:answer3,4:answer4,5:answer5,'

// 2. Split to array 
var string = string.split(",");

// 3. EACH 
$.each(string, function(key, val) {

    var answer = answer.split(":");
    $.each(answer, function(key1, val1) {
       // output textfield with id of key1 and value of val1 
    });

});

I can go through the first set of data, that is comma separated, but not the next (:). How do I do that?

Upvotes: 1

Views: 111

Answers (4)

Besi
Besi

Reputation: 22939

Nothing against your home-made string of course, but have you considered using JSON for encapsulating data in a string. While JSON is universally usable it is probably the perfect match for JavaScript.

So if you would encode your data as follows it would really be a piece of cake to parse:

var data = [
    {
        "id": 1,
        "answer": "answer1"
    },
    {
        "id": 2,
        "name": "answer2.. etc."
    }
];

So now you can access your data very easily using array and property notation:

alert (data[0].answer);

Update: So in if you are lucky and your Rails app is on version 3.1 then adding support for JSON is really a piece of cake:

For basic JSON support the only thing you need to do is this:

# GET /answers/1
# GET /answers/1.json
def show
  @answer = Answer.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json do
        render json: @answer
    end
  end
end

Upvotes: 1

georg
georg

Reputation: 214959

You can use String.replace as an iterator:

var string = '1:answer1,2:answer2,3:answer3,4:answer4,5:answer5,'

var html = []

string.replace(/([^:]+):([^,]+)(,|$)/g, function(_, key, val) {
     html.push("<input name='" + key + "' value='" + val + "'>")
});

alert(html.join("\n"))

Upvotes: 2

Vikk
Vikk

Reputation: 3373

$.each(string, function(key, val) {

        var answer = val.split(":");

        key1 = answer[0];
        val1 =  answer[1];

        alert(key1+"--"+val1);
    });

Upvotes: 4

nakhli
nakhli

Reputation: 4059

it should be var answer= val.split(":"); instead of var answer = answer.split(":");

Upvotes: 4

Related Questions