Modify Json to use into React beautiful Drag and drop - json

I am using this library for react drag and drop functionality. However, my json is in this format
[
{
"id": "5f7",
"itemName": "ABC"
},
{
"id": "780",
"itemName": "CRD"
},
]
However, all the tutorial points, i will need something like this:
[
'item1': {
"id": "5f7",
"itemName": "ABC"
},
'item2': {
"id": "780",
"itemName": "CRD"
}
]
So how can i modify my json and add id for drag and drop functionalities. Even if there is any other way of achieving this then i really appreciate that.

You can do this with plain javascript, loop through your item's array with map() and create a new array that encapsulates the item, see following example:
var currentArray = [{
"id": "5f7",
"itemName": "ABC"
},
{
"id": "780",
"itemName": "CRD"
}];
var result = "", sep = "";
currentArray.forEach((el, i) => {
result += sep + "\"item" + (i+1) + "\"";
result += ": " + JSON.stringify(el);
sep = ", ";
});
console.log(JSON.parse("{" + result + "}"));

Related

Groovy Collect values from nested json arrays

I am trying to map a nested json into a flat file but have an issue referencing between different arrays.
I get it working for each array separately but can't figure out how to properly reference the parent ids to be included. I tried working with indexes and copying the event.id and event.lots.id on the pricings objects but that got really messy.
Maybe I am just on the wrong track or didn't have the right idea on how this might work.
Code
def body = message.getBody(String.class)
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(body)
def i_events = object.events
def i_lots = object.events.lots
def i_pricing = object.events.lots.pricings
def o_values = i_pricing.flatten().collect {"(" + "'" + i_events.collect{it.id}[0] + "'" + "," + "'" + i_lots.collect{it.id}[1] + "'" + "," + "'" + it.id + "'" + "," + "'" +it.name + "'" + ")" }.join(',')
//just using print for testing
println o_values
Result
('event_id1','[id A, id B]','p id1','TEST 1'),('event_id1','[id A, id B]','p id2','TEST 2')
Expected Result
('event_id1','id3','p id1','TEST 1'),('event_id1','id A','p id2','TEST 2')
Sample input
{
"events": [
{
"id": "event_id1",
"name": "Test Event 01",
"to": "2021-08-27T02:30:00.000Z",
"from": "2021-08-26T16:15:00.000Z",
"parkingTo": "2021-08-27T02:30:00.000Z",
"parkingFrom": "2021-08-26T14:15:00.000Z",
"landmarkId": "111",
"slug": "test-event1",
"live": true,
"lots": [
{
"id": "id1",
"name": "Lot 1",
"pricings": []
},
{
"id": "id2",
"name": "Lot 2",
"pricings": []
},
{
"id": "id3",
"name": "Lot3",
"pricings": [
{
"id": "p id1",
"name": "TEST 1"
}
]
}
]
},
{
"id": "event_id2",
"name": "Test Event 2",
"to": "2020-08-31T17:00:00.000Z",
"from": "2020-08-31T14:00:00.000Z",
"parkingTo": "2020-09-01T08:45:00.000Z",
"parkingFrom": "2020-08-31T12:45:00.000Z",
"landmarkId": "111",
"slug": "test-event2",
"live": true,
"lots": [
{
"id": "id A",
"name": "lot A",
"pricings": [
{
"id": "p id2",
"name": "TEST 2"
}
]
},
{
"id": "id B",
"name": "lot B",
"pricings": []
}
]
}
],
"meta": {
"total": 2,
"firstElement": 0,
"lastElement": 2
}
}
Something like this should work (it's hard to say, as your example input seems different to your expected output)
I added a quote method for if the values contain a ', you will need to think if you need this, and how you're going to escape things
def escape(String s) {
"'${s.replaceAll("'", "\\\\'")}'"
}
def output = new JsonSlurper().parseText(body).events.collectMany { event ->
event.lots.collectMany { lot ->
lot.pricings.collect { pricing ->
"(${escape(event.id)}, ${escape(lot.id)}, ${escape(pricing.id)}, ${escape(pricing.name)})"
}
}
}.join(',')

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

How to retrieve/display title, units, copyright along with JSON data in Highcharts

I have successfully implemented code for a JSONP request, retrieving data for multiple countries and displaying them as lines in a chart.
However, I would need to get the title, units, copyright etc. from the JSON as well, to be able to display that elements on the graph too.
Now, I wonder how this could be done.
The JSON response could look like this:
[
[
"series",
[
{
"data": [
[
2007,
2239300
],
[
2008,
2237490
],
[
2009,
2167070
],
[
2010,
2204450
]
],
"name": "France"
},
{
"data": [
[
2007,
2324234
],
[
2008,
3456352
],
[
2009,
1241422
],
[
2010,
4543231
]
],
"name": "Germany"
}
]
],
[
"title",
{
"text": "Title here"
}
],
[
"yAxis",
{
"text": "The units here"
}
]
]
My client's code would need to be changed then. For the moment it looks like this:
$.getJSON(url, {selectedCountries: "France,Germany,Switzerland", type: "jsonp"})
.done(function(data)
{
options.series = data;
var chart = new Highcharts.Chart(options);
})
.fail(function(jqxhr, textStatus, error)
{
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
})
And I guess it must turn into something like this:
options.series = data['series']['data'];
options.title = data['title'];
But that doesn't work. Could anyone give me a hint what I should do? Thanks a lot!
Ok, got it going finally. One has to pass the JSON as an object (and not an array, and neither as string (so, no quotes like ' or " around the object!). Works like a charm here on fiddle.
Here the code:
$(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline',
marginBottom: 50
},
series: [{}]
};
data = {
"title": {
"text": "Here goes the title"
},
"yAxis": {
"title": {
"text": "Here go the units"
}
},
"series": [{
"name": "France",
"data": [[2006,2189260],[2007,2239300],[2008,2237490],[2009,2167070],[2010,2204450]]
}]
};
options.series = data["series"];
options.title = data["title"];
options.yAxis = data["yAxis"];
var chart = new Highcharts.Chart(options);
});
Thanks a lot for Sebastian Bochan's great support!

How do i put JSON data in html page

This is my json data which i get in rest client.
I am fetching firstName,lastName,emailId of my employee table and i need to insert this data into my html page.
how to do that please help
i am struck here.
[
{
"firstName": "Ramu",
"lastName": "Poola",
"emailId": "asdfg#gmail.com"
},
{
"firstName": "Dash",
"lastName": "Board",
"emailId": "admin#gmail.com"
},
{
"firstName": "Srinivas",
"lastName": "Grandhi",
"emailId": "123grandhi#gmail.com"
}
]
I think better to use javascript or jquery here..
Check below code...
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
There are many ways to do this, most ways probably use javascript. Do you want to display the results in a table?
If so you could use jQuery Datatables:
http://www.datatables.net/examples/data_sources/js_array.html
This will also allow give you a lot of table features like sorting and searching without you having to write the code yourself.
var dataSet = [ {
"firstName": "Ramu",
"lastName": "Poola",
"emailId": "asdfg#gmail.com"
},
{
"firstName": "Dash",
"lastName": "Board",
"emailId": "admin#gmail.com"
},
{
"firstName": "Srinivas",
"lastName": "Grandhi",
"emailId": "123grandhi#gmail.com"
}
]
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "title": "firstName" },
{ "title": "lastName" },
{ "title": "emailId" }
]
} );
Alternatively you could go for a framework like AngularJS and just use a ng-repeat to render your table. This is a whole framework though, but it works well with rest apis
you need just set ant div with one id or class name aftre put this
content on that div
var logData = JSON.parse(data);
var $grouplist = $('#surat');
$.each(logData, function() {
var dthtml="";
dthtml += "<table><tr><td align='center'>"+this.firstname+"<br/></td><td><table><tr><td><img src='img/login.png'>"+this.lastname+"</td></tr><tr><td>"+this.emailId+"</td></tr></table></td></tr></table>";
$(dthtml).appendTo($grouplist);
});
<div id='surat'></div>

BackboneJS How to fetch specific value from API JSON file

I have a BackboneJS Application where I want to fetch a specific value from a JSON API.
The JSON file has this structure:
"data": {
"title": "some title",
"startDate": "some start date",
"endDate": "some enddate",
"description": "description blablabla ",
"contest_id": 10,
}
I want to fetch the "contest_id". So I have this Backbone Model:
CompetitionQuestion.CompetitionQuestionModel = Backbone.Model.extend({
url: function() {
return App.APIO + '/i/contest/' + this.contest_id;
},
defaults: {
"data": []
}
});
This gives me /i/contest/undefined Why is that?? I cant do:
return App.APIO + '/i/contest/' + this.data.contest_id;
Can someone tell me what I'm doing wrong?