0

Im looking for a simple script to convert JSON objects to Javascript objects, specifically being able to make an ajax call in jQuery and then convert all of the JSON that comes back into Javascript objects for me.

I've used the mapping plugin in KnockOut.js: https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output

Which nicely takes my JSON result and creates the relevant objects in knockout.

Anything currently exist to do this without knockout?

1
  • 6
    Um, JSON.parse(...)? Commented Mar 4, 2012 at 0:59

4 Answers 4

4

jquery automatically does this for you.

from the JQuery documentation for getJSON:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});
Sign up to request clarification or add additional context in comments.

Comments

3

Just specify the dataType setting as 'json' in the $.ajax call, or use the $.getJSON method, and the JSON result will automatically be parsed into a Javascript object.

Comments

-1

I'm guessing here, but if you want to convert them into already defined javascript objects you need the second argument in the JSON.parse function. Check MDN's documentation https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse.
Very simple example.

JSON.parse(json,function(prop,val){
  if(prop==='objName'){
    new myObj(val);
  }
});

Comments

-2

For use in JQUERY: http://api.jquery.com/jQuery.parseJSON/ For use in simple JS: https://github.com/douglascrockford/JSON-js (look at json.js or json2.js)

Knowing that it's well-formed:

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

Comments

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.