4

Can anyone tell me how to generate json data from SharePoint lists in the below format using java script.

var jsonArray = [
    { "user": { "id": 100, "screen_name": "d_linq" } },
    { "user": { "id": 130, "screen_name": "c_bill" } },
    { "user": { "id": 155, "screen_name": "b_mskk" } },
    { "user": { "id": 301, "screen_name": "a_xbox" } }
]
4

You can perform a REST request, and have the results returned in a JSON object:

$.ajax({
    url: "http://site url/_api/web/lists/GetByTitle('Test')/items",
    type: "GET",
    headers: {
        accept: "application/json;odata=verbose",
        content-type: "application/json;odata=verbose"
    },
    success: function(data) {
        // you can find the items in JSON format under data.results
    },
    error: function(data, errorCode, errorMessage) {
        // error handling
    }
});

More on REST here.

  • But how to build json string dynamically from rest query results.. – user17274 Oct 1 '14 at 15:08
  • The returned data is already in JSON format. If you want it in string format, then simply do JSON.stringify(data). – wjervis Oct 1 '14 at 15:10
3

This seems like it's as much a JS question as it is a SharePoint question:

Step 1 is get the results

Step 2 is process the results yourself to make an object that looks like you want

Example (assuming you're using jQuery):

// Step 1: Get the results
$.getJSON("/_api/web/siteusers", function(data) {
    //remove these console.log statements before using in production
    //use your browser dev tools to inspect the objects
    console.log("Returned JSON Data:");
    console.log(data);
    // Step 2: Process the results into the form you want
    var results =[];
    for (var i = 0; i < data.value.length; i++) {
        results.push({"user": { "id": data.value[i].Id, 
                    "screen_name": data.value[i].Title }});
    }
    // do other work with your results below here
    console.log("Object we created based on the results:");
    console.log(results);
});

Be aware, that this is going to give you a bunch of system and app accounts that you probably don't want to enumerate, but you can filter them off by checking if an Email property is defined in the original JSON results 'value' array.

I included all the console logging so you can see what these objects look like using your browser dev tools, and pick the fields you actually want to use.

Oh yeah! This will only work on the 2013 platform, if you need this solution on an older platform you'll need to specify which version (but it can be done, generally)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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