I have following json data
var data = [
Object {
Data = 3,
Label = "Statement -2"
},
Object {
Data = 3,
Label = "this is a very long stat...s a very long statement"
}
]
I want to convert it into the following:
var data: [{
data : [[0,50]],
label : "Comedy"
}, {
data: [[0, 10]],
label : "Action"
}, {
data: [[0, 60]],
label : "Romance"
}, {
data: [[0, 20]],
label : "Drama"
}]
Can any one help me?
Your Source JSON is not right.
Change your source JSON like this, and call method to transform.
var data = [
{
data : 3,
Label : "Statement -2"
},
{
data : 6,
Label : "this is a very long stat...s a very long statement"
}]
for(var item in data){
data[item].data = [0,data[item].data]
}
You could iterate over your array of objects and use toArray() to get your array of arrays.
for (var i=0;i<data.length;i++) {
data[i] = data[i].toArray();
}
Not tested thou ;-)
Related
How can i acces the first item id?
using (var http = new HttpClient())
{
var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
^^^^^^ // Also tried with JObject instead of JArray, both don't work
var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
Console.WriteLine(champion); // ^ [0] here because the JSON starts with an [
}
Example JSON result (made it smaller because the original JSON is over 21500 characters, made sure its valid with https://jsonlint.com, here is the original JSON response: https://hastebin.com/sacikozano.json)
[{
"key": "Gragas",
"role": "Jungle",
"overallPosition": {
"change": 1,
"position": 13
},
"items": {
"mostGames": {
"items": [{
"id": 1402,
"name": "Enchantment: Runic Echoes"
},
{
"id": 3158,
"name": "Ionian Boots of Lucidity"
},
{
"id": 3025,
"name": "Iceborn Gauntlet"
},
{
"id": 3065,
"name": "Spirit Visage"
},
{
"id": 3742,
"name": "Dead Man's Plate"
},
{
"id": 3026,
"name": "Guardian Angel"
}
],
"winPercent": 50.45,
"games": 300
}
}
}]
With JArray i get the following error: Accessed JObject values with invalid key value: 0. Object property name expected.
With JObject i get the following error: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Thanks in advance, i hope i explained it well
It should be:
var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
The outermost "items" property has a single object as its value, not an array, so [0] is not needed in ["items"][0]. Similarly "mostGames" has a single object value so the [0] is not needed in ["mostGames"][0].
Sample fiddle.
Note that if "items" is sometimes an array of objects, but sometimes is a single object instead of an array of one object, you can introduce the following extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> AsArray(this JToken item)
{
if (item is JArray)
return (JArray)item;
return new[] { item };
}
}
And do:
var champion = (Uri.EscapeUriString(res[0]["items"].AsArray().First()["mostGames"]["items"][0]["id"].ToString()));
I am a beginner in using jQuery Float Chart. Now I try to bind the chat with server side values. I need to build an array structure like below.
data = [{
label: 'Test 1',
data: [
[1325376000000, 1200],
[1328054400000, 700],
[1330560000000, 1000],
[1333238400000, 600],
[1335830400000, 350]
]
},];
My Server Response
My question is how to push items in this array of array. I already try to build an array like this:
var data = new Array();
var chartOptions;
$.each(graphdata, function (key, value) {
data.push({
label: value.label,
data: $.each(value.data, function (key, value) {
Array(value.X, value.Y);
})
})
});
Edits
Graph shows in webpage
But it's not working.
The problems is that $.each return collection that iterates on - the collection you don't want to.
You can use underscore library that contains function map to project value into another:
var postData = [{label:"test1", "data": [ {X: "10", Y:"11"}, {X: "12", Y: "13"}] }];
var data = []
$.each(postData, function (key, value) {
data.push({
label: value.label,
data: _(value.data).map(function(innerVal) {
var arr = new Array();
arr.push(innerVal.X);
arr.push(innerVal.Y);
return arr;
})
})
});
Here is jsFiddle: click!
I have a JSON object that looks like this
{
"totalCount": 2,
"students": [{
"name": "abc",
"data": {
"Maths": 20,
"Science": 25
},
"score": 10.0
},
{
"name": "xyz",
"data": {
"Maths": 44,
"Science": 12
},
"score": 11.0
}]
}
I want to deserialize this JSON object to an IEnumerable<String> that contains all the names.
I want -
private IEnumerable<String> GetAllNames(string json) to return ["abc","xyz"]
This is just sample data (and not homework!!). Any advice on how to achieve this would be appreciated. I'm using Newtonsoft library but haven't been able to do this effectively yet. I do not want to iterate through the objects and construct the list myself, any direct way of doing this?
EDIT -
This is what I'm doing currently
var studentList = new List<string>();
var json = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach (var data in json.students)
{
catalogsList.Add(data.name.toString());
}
return catalogsList;
Try this:
private IEnumerable<string> GetAllNames(string json)
{
JObject jo = JObject.Parse(json);
return jo["students"].Select(s => s["name"].ToString());
}
I have a data table witch i serialize into a json and then parse to my view code where i use J Query to get those values.
When i use
document.getElementById('Name').value = UserInfo.Name;
the
Userinfo.Name = null,
what am i doing wrong for not being able to read my UserInfo.
Could someone please tell me how i can get the values out of UserInfo.
Below is all my code:
C# Code:
public JsonResult SearchForUser(int id)
{
string Sjson = JsonConvert.SerializeObject(DataTable, Formatting.Indented);
return Json(Sjson, JsonRequestBehavior.AllowGet);
}
J Query code:
$.post("SearchForUser", { id: id }, function (UserInfo) {
if (UserInfo != "")
{
document.getElementById('Name').value = UserInfo.Name;
document.getElementById('Surname').value = UserInfo.Surname;
}
});
Json :
"[ {
"UserId": 5,
"UserName": "JamesBond#MI6.com",
"UserPassword": "007",
"Name": "James",
"RoleId": 2,
"EmployeeId": 5,
"Active": true,
"Name1": "James",
"Surname": "Bond",
"IdNumber": "007",
"PassportNumber": "700",
"PhysicalAddress": "MI6",
"PostalAddress": "MI7",
"TelNumber": "0126659007",
"SelNumber": "0837777007",
"EmailAddress": "JamesBond#MI6.com",
"Designation": "Spy",
"DateEmployedFrom": "2013-06-19T00:00:00",
"Active1": true } ]"
Extra:
I am working with MVC razor.
Thanks in advance.
Edit still can't access values (This edits are in reply with answers)
It looks like your JSON object is an array with one item. In that case you should be accessing UserInfo[0].Name. Also verify that document.getElementById('Name') does indeed find an element.
Also, since you're using jQuery, document.getElementById('Name') = UserInfo[0].Name could be rewritten as $('#Name').val(UserInfo[0].Name).
Use var info=jQuery.parseJSON(UserInfo); to parse the value and then info.Name will give you result
DEMO
Like your JSON object structure Check here
Lets say i have the following JSON
{
"data": [
{
"from": {
"name": "aaa bbb",
},
"actions": [
{
"name": "Comment",
"link": "http://...
},
{
"name": "Like",
"link": "http://.."
}
],
},
And i have
JSONObject wallData = helper.Get("/me/feed");
if (wallData != null)
{
var data = wallData.Dictionary["data"];
List<JSONObject> wallPosts = data.Array.ToList<JSONObject>();
}
foreach (Facebook.JSONObject wallItem in wallPosts)
{ ... }
Which stores me whole feed into wallData and 'data' object into wallPosts.
So then i can access the wallItem.Dictionary["from"].Dictionary["name"], and i get "aaa bbb".
But i can't get inside the actions array
The wallItem.Dictionary["actions"].Dictionary["name"] doesn't work.
Any idea
You need to do something like wallItem.Dictionary["actions"][0].Dictionary["name"] because "actions" is an array.
On a different note...its neater if u directly into a class...like this
var jSerializer = new JavaScriptSerializer();
var jsonObject = jSerializer.Deserialize<DataObject>(json);
The DataObject will be a class which emulates ur JSON data in a strongly typed class. Depending on the size of ur Json you will not have to use a lot of strings in your code.