Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I don't know why you'd want to do this - why not just add the property <em>before</em> you stringify it?</p> <p>But if you must, given a string that contains JSON:</p> <pre><code>var myJSON = '{"prop1":"val1","prop2":"val2"}'; </code></pre> <p>You can easily add a property to the beginning by doing this:</p> <pre><code>myJSON = '{' + '"sn":"1",' + myJSON.substr(1); </code></pre> <p>Or add it to the end:</p> <pre><code>myJSON = myJSON.replace(/}$/, ',"sn":"1"' + '}'); </code></pre> <p>Or use whatever other combination of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" rel="nofollow">String</a> manipulation functions takes your fancy...</p> <p>If you want to add the new property in a specific place within the string, say inside a nested object or array or something, well, again some kind of regex or combination of <code>.indexOf()</code> and <code>.substr()</code> or something could do it, but really I think it's nuts to approach it this way.</p> <p>Obviously the above code can be wrapped up in a function, and <code>'"sn":"1"'</code> can be replaced with a parameter or variable name or whatever - but <em>why</em>?</p> <p>Note also that I've assumed above that there will be at least one existing property and inserted a comma accordingly- up to you to make that smarter if you want to allow for empty objects.</p> <p>P.S. There aren't "JSON strings" and "JSON objects": <em>all</em> JSON is a string. In JavaScript one way of creating objects is with the object literal syntax that inspired JSON, but there's no such thing as a JSON object.</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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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