Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript objects with JSON
    primarykey
    data
    text
    <p>Im sure this must have been asked before but I can't find an example on SO. I have a JSON string that starts out life as something like this:</p> <pre><code>{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}} </code></pre> <p>The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.</p> <p>So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.</p> <pre><code>function changeJSON(node, value) { json = JSON.parse($('#json').val()); json.selection[node] = value; delete json.changed; json.changed = {node:value}; $('#json').val(JSON.stringify(json)); } </code></pre> <p>"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) I.e. if I called the function with changeJSON("BC","HC") the JSON string becomes:</p> <pre><code>{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}} </code></pre> <p>I understand what javascript is trying to do but I want the changed element to be what my variable contains i.e. </p> <pre><code>,"changed":{"BC","HC"} </code></pre> <p>and not</p> <pre><code>,"changed":{"node","HC"} </code></pre> <p>I'd love someone to tell me what I am doing wrong!?</p> <p>EDIT</p> <p>Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload