0

I have a JSON String in a JavaScript var, how I can loop through JSON string to make script like this output?

INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');

Is there is any direct way to fill a table from a json string?

JSON Example:

{"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]}
2
  • can u please give a json example Commented Mar 19, 2014 at 4:24
  • I edited the question to add the example. Refresh the page, please. Commented Mar 19, 2014 at 4:27

2 Answers 2

2

We assign a variable name to the json object

var table = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};

Using jquery

loop over the variable table which have the property table.

 $.each(table.table,function(index, item){
    //INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');     
     console.log("INSERT INTO table VALUES('"+ item.id + "','"+ item.name + "','"+ item.nick + "','"+ item.year +"')");
});

take a look in jsfiddle http://jsfiddle.net/628Cb/

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

1 Comment

I got an error: Uncaught TypeError: Cannot read property 'length' of undefined But I fixed: table= JSON.parse(table); Thanks!
1

You can use the for loop to iterate over the array contained by the table object.

var p = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};
 var arr = p["table"];
 for(var i=0;i<arr.length;i++){
    var obj = arr[i];
    alert(obj["id"] + " "+ obj["name"] + " "+ obj["nick"]+ " "+obj["year"]);   
    INSERT INTO table VALUES (obj["id"], obj["name"], obj["nick"], obj["year"]);   
}

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.