Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON string parsing in Javascript

I have some JSON which has been passed from a servlet and is stored in xmlhttp.responseText. I want to decompose this JSON so that i can have values of data, size, style, name, etc. Also I wish to have the widget value to be in separate variable.

Here is the JSON:

{
  "widget vlaue=2": {
    "debug": "on",
    "window": {
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500
    },
  },
  "image": { 
    "src": "Images/Sun.png",
    "name": "sun1",
    "hOffset": 250,
    "vOffset": 250,
    "alignment": "center"
  },
  "text": {
    "data": "Click Here",
    "size": 36,
    "style": "bold",
    "name": "text1",
    "hOffset": 250,
    "vOffset": 100,
    "alignment": "center",
    "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
  }
}    

I have tried this:

obj = JSON.parse(xmlhttp.responseText); 

but this failed. I could not find anything related to it online. Can anyone please help me with this?

like image 255
typedefcoder2 Avatar asked Jun 25 '26 05:06

typedefcoder2


1 Answers

From json.org :

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

However JSON.parse is still recommended:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

Perhaps there is something wrong with your JSON, visit jsonlint.com for a free web-base JSON validator.

like image 194
Gapton Avatar answered Jun 26 '26 20:06

Gapton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!