How can I pass the json object using button with onclick

Viewed 45

I have a simple json javascript obj. I am trying to pass the object with onclick button to process function and display contents in console.log

I have tried sending as js object and also as JSON.stringify... both are having issues... ex: undefined Uncaught SyntaxError: "[object Object]" is not valid JSON

Q: how can I pass the json using onclick to the process function and successfully display its contents.

<script>

//set json obj

var obj = {  
        "first":       "joe", 
        "last":       "smith",   
        "cell":       "213 111 2222"
};

var jsonstr = JSON.stringify(obj);

</script>


<script>

// various button tries

output = "";


output += "<div >" + 

"<button class=\"buttonform2_16_small\" onclick=\"process(" + obj + ")\">obj </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + obj + "')\">obj 2 w q</button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process(" + jsonstr + ")\">jsonstr </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + jsonstr + "')\">jsonstr w q </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + txtstr + "')\">text w quote </button>"
+ "<br>"
+ "</div>"; 

$('#list').html( output );


</script>


<script id="scr process"> 

//process 

function process(item) {

    console.log('item is : ' + item);

    console.log('item first name is : ' + item.first);

    var res = JSON.parse(item);

    console.log('res  is : ' + res);


1 Answers

You should escape it, i.e mainly replace " with &quot;

function esc_attr(string) {
  if (!string) {
    return "";
  }
  return ("" + string).replace(/[&<>"'\/\\]/g, function(s) {
    return {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': '&quot;',
      "'": '&#39;',
      "/": '&#47;',
      "\\": '&#92;'
    }[s];
  });
}

var obj = {
  something: {
    another: 12,
    arr: ['a', 'b', 'c'],
    evil: "don't &j39'\!$K!d1//93^%^do <scri" + "pt>alert(12)</sc" + "ript>"
  },
  bool: false
}

var button = "<button onclick='console.log(" + esc_attr(JSON.stringify(obj)) + ")'>click me</button>"
document.body.innerHTML = button;

Related