15

How to store Json string in a hidden input field. Well, I could do it programmatically, but something wrong with escaping. Since my string is moderately long, it is hard to escape " char for all the names. Please explain how it works programmatically (phase 1), as the console output looks same.

[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]test2.html:21 [{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}] test2.html:22 PASSED PHASE 1
jquery.min.js:16Uncaught SyntaxError: Unexpected end of input

thanks,

bsr.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title> 
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
        <input type="hidden" id="jsondata" />
        <input type="hidden" id="jsondata2" value="[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]"/>


    <script >
            $(document).ready(function() {  

            myItems = [{"X":0,"Y":0,"W":0,"H":500},
                   {"X":358,"Y":62,"W":200,"H":500}]

            console.log(JSON.stringify(myItems));
            $("#jsondata").val(JSON.stringify(myItems));
            console.log(document.getElementById("jsondata").value);
            console.log("PASSED PHASE 1");

            var obj = jQuery.parseJSON($("#jsondata2").val());
            console.log(obj.length);    
            console.log("PASSED PHASE 2");           
        }); 
    </script>
</body>
</html>

Edit:

the following code works.. not sure whether it is correct. so will mark a good explanation as answer. thanks.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title> 
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
        <input type="hidden" id="jsondata" />
        <input type="hidden" id="jsondata2" value='[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]'/>


    <script >
            $(document).ready(function() {  

            myItems = [{"X":0,"Y":0,"W":0,"H":500},
                   {"X":358,"Y":62,"W":200,"H":500}]

            console.log(JSON.stringify(myItems));
            $("#jsondata").val(JSON.stringify(myItems));
            console.log(document.getElementById("jsondata").value);
            console.log("PASSED PHASE 1");

            var obj = jQuery.parseJSON($("#jsondata2").val());
            console.log($("#jsondata2").val()); 
            console.log(obj[0].H);  
            console.log("PASSED PHASE 2");           
        }); 
    </script>
</body>
</html>
4
  • 1
    Are you wanting to store this in a hidden field so you can use it later or were you thinking to submit it via a form? Commented May 9, 2011 at 17:50
  • I am storing the Json string in a hidden field, and the value is render through template at the server side. At client side, I parse it into object array and use it for further representation Commented May 9, 2011 at 18:04
  • Ok.. the following worked... <input type="hidden" id="jsondata2" value='[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]'/> , if someone has a good explanation, I will mark it as answer.. thanks for all ur help Commented May 9, 2011 at 18:11
  • If you're rendering it on the server side why not just render it as a script block and use it right away without parsing? Security considerations? Commented Dec 29, 2011 at 15:31

5 Answers 5

12

You can do something like this, but it's pretty bad, HTML :

<textarea id="jsondata" sytle="display:none"></textarea>

and JS

$(function(){

    var myItems = [{"X":0,"Y":0,"W":0,"H":500}, {"X":358,"Y":62,"W":200,"H":500}]

    $("#jsondata").val(JSON.stringify(myItems));

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

1 Comment

It is a good solution, but there is a small issue with it. If the values will contain a &quot; string the JSON will break because the Textarea is automatically decoding HTML entities so it will convert to be ". e.g. { x: "a", y: "b&quot;c"} will converted to be { x: "a", y: "b"c"}
8
<input type="hidden" id="jsondata2" value="[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]"/>

is not correct. Use single quotes ' instead of the double quotes " in the value string to fix it (or escape the ")

<input type="hidden" id="jsondata2" value="[{'X':0,'Y':0,'W':0,'H':500},{'X':358,'Y':62,'W':200,'H':500}]"/>

4 Comments

Just the SO colorization is a good helper for finding issues like that.
that is not conclusive, see the example from jQuery API for parseJSON var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" ); .. this works
also, json.org , By far the most common error I’ve encountered relates to object keys. In JSON (unlike in JavaScript) these MUST be double-quoted strings. In fact, ALL strings in JSON must be enclosed in double quotes (JavaScript also allows single quotes; JSON does not). ref: simonwillison.net/2006/Oct/11/json
What will happen if {'X':0,'Y':0,'W'w':0,'H':500} comes..??? The value will be incorrect..
4

The html markup is invalid ... if you run html validator againt the first html (non working one) you will find errors on the line...

1 Comment

good catch.. first error about namespace, because the file was originally was an xhtml file, then I just removed few parts.. the second error, about extra spacing, not sure.. need to read more.. thanks
2

See answer about quotes.

Reason is simple -- when you have this code:

[sometag someattr="qwerty"123":cxzcxz"/]

browser understands it as:

[sometag someattr="qwerty"/]

And last part (123":cxzcxz") just throwing off as a junk. So for your concrete case parseJSON tries to work with just this:

[{

But you think it`s a full string like:

[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]

So better you should encode your json before putting in a value of hidden field on server side.

Comments

0

Try the code below, it looks like you have an array not an object to me.

 myItems = { data : [{"X":0,"Y":0,"W":0,"H":500},
                     {"X":358,"Y":62,"W":200,"H":500}] };

5 Comments

I think you are missing the point of the question. He is asking why when the data is injected to the field via javascript it works, but when the data is in the value attribute of the field it does not.
@Gazler : not is not my understanding. I see stringify() work and parseJSON() not work. parseJSON() fails because it is not valid JSON. I give valid JSON : solved.
@Hogan, if you run the code, you'll see that the two methods are running off of different data. Both stringify() and parseJSON() work.
Hogan I changed data as u said, and the input to corresponding <input type="hidden" id="jsondata2" value="{"data":[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]}"/> , still same error. So, it could be related to escaping the char "
value="{"data":[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]}" is wrong as @rachet pointed out you can't have " inside an attribute delimited by ". You have to "mix it up" with " and '.

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.