Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

If we take this code example, we can see we need to call a lot of methods to get to our results (.getEnumerator(), .get_current(), .get_title(), .get_title())

var siteUrl = '/sites/MySiteCollection';

function retrieveAllListProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();

    clientContext.load(collList);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    var listInfo = '';

    var listEnumerator = collList.getEnumerator();

    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        listInfo += 'Title: ' + oList.get_title() + ' Created: ' + oList.get_created().toString() + '\n';
    }
    alert(listInfo);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Is there any built in method will will return the results in the form of a simple data structure, e.g. an array of objects, each object representing a list item, e.g:

[
    {ID:1, Title:"value", Author:"value" ...},
    {ID:2, Title:"value", Author:"value" ...},
    {ID:3, Title:"value", Author:"value" ...}
    ...
]

Or if I could access the original JSON returned from _vti_bin/client.svc/ProcessQuery as that has a clean enough structure.

My goal is to pass on a clean data structure to a templating engine like doT.js or Handlebars.js, without the need to loop through and manually build a new data structure using the methods outlined above. Seems like an unnecessary step when a decent structure is right there in the JSON response.

share|improve this question
add comment

2 Answers

There is no built in method in SharePoint 2010 JavaScript Object Model (JSOM) that allow to return list items in JSON format, but it could be accomplished with an Object to JSON serializer

JSON.stringify

JSON stringifier function is intended for convering JavaScript data structures into JSON text.

How it works

Let's see how to retrieve task item properties from Tasks list

function loadTasks()
{
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getByTitle("Tasks");
        var viewXml = '<View><RowLimit>1200</RowLimit></View>';
        var query = new SP.CamlQuery();
        query.set_viewXml(viewXml);
        var items = list.getItems(query);
        context.load(items,"Include(Title,AssignedTo,Status,Priority)");
        context.add_requestSucceeded(onLoaded);
        context.add_requestFailed(onFailure);
        context.executeQueryAsync();
        function onLoaded() {
            var tasksEntries = [];
            var itemsCount = items.get_count();
            for (i = 0; i < itemsCount; i++) {
                var item = items.itemAt(i);
                var taskEntry = JSON.stringify(item.get_fieldValues());
                tasksEntries.push(taskEntry);
            }
        }
        function onFailure() {

        }
}

Note:

a)Items properties that should be initialized are explicitly specified using "Include(Title,AssignedTo,Status,Priority)"

b)for retrieving field properties(name/value) SP.ListItem get_fieldValues is used

c)finally JSON.stringify is used to convert field properties object to JSON

Result for tasksEntries:

[
  {"Title":"Task 1","AssignedTo":{"$b_1":"Developer","$M_1":1},"Status":"Not Started","Priority":"(2) Normal"},
  {"Title":"Task 2","AssignedTo":{"$b_1":"Developer","$M_1":1},"Status":"In Progress","Priority":"(3) Low"}
  {"Title":"Task 3","AssignedTo": {"$b_1":"Developer","$M_1":1},"Status":"Completed","Priority":"(2) Normal"}
]
share|improve this answer
add comment

You could always construct your own DVWP to return your desired JSON for use in a templating engine. I've been playing around with this for a couple days and really starting to see it's potential. http://www.metaengine.com/2012/12/Returning-JSON-from-the-SharePoint-DVWP-aka-poor-mans-GetSiteData

Server does the work fetching the data and you can set it up to supply you with whatever inforamtion you need for your templates.

share|improve this answer
    
Very cool approach! –  Dave Wise Jan 29 '13 at 18:03
    
I used a similar technique a couple of years ago, converting data views to JSON with XSL, but I'd rather keep the dynamic query ability rather than have to set up a data view each time –  Fergal Jan 29 '13 at 20:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.