i am trying to convert a json value to a flat csv based on the field that is selected by user . My json looks like
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
Ive been able to collect the values of all occurences and store it as a csv, but I want to save the details from the root itself..
If I select Time, the csv output should look like,
"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"
Is it possible to flatten the json.. I will add the json fiddle link to show where Ive reached with this thing..
http://jsfiddle.net/JHCwM/
Here is an alternative way to flatten an object into key/value pairs, where the key is the complete path of the property.
let data = {
pc: "Future Crew",
retro: {
c64: "Censor Design",
amiga: "Kefrens"
}
};
let flatten = (obj, path = []) => {
return Object.keys(obj).reduce((result, prop) => {
if (typeof obj[prop] !== "object") {
result[path.concat(prop).join(".")] = obj[prop];
return result;
}
return Object.assign(result, flatten(obj[prop], path.concat(prop), result));
}, {});
}
console.log(
flatten(data)
);
Your data value is not a JSON (string) - it's an object. There are many ways to 'flatten' this object, may be this little function might be helpful:
var recMap = function(obj) {
return $.map(obj, function(val) {
return typeof val !== 'object' ? val : recMap(val);
});
}
And here's how it can be used. )
There is a npm lib just for this with a lot of options: https://mircozeiss.com/json2csv/
# Global install so it can be called from anywhere
$ npm install -g json2csv
## Generate CSV file
$ json2csv -i data.json -o out.csv --flatten-objects
Try looking here:
http://www.zachhunter.com/2011/06/json-to-csv/
and here:
How to convert JSON to CSV format and store in a variable
Try the following :
http://codebeautify.org/view/jsonviewer
Use Export to CSV button
Check this out to flatten the Json
// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
$.each(data, function(i, e) {
if (e.Children.length>0) {
var ccd = e.Children;
delete e.Children;
finalData.push(e);
loopJson(ccd);
} else {
delete e.Children;
finalData.push(e);
}
});
}
console.log(finalData);
Here is Js fiddle link http://jsfiddle.net/2nwm43yc/
Related
I am trying to supply some data to a Javascript Function but right now i am unable to convert it to desired format.
The Correct Format that is Working is below.
const eventsArr = [
{
day: 1,
month: 1,
year: 2023,
events: [
{
title: "asdEvent 1 lorem ipsun dolar sit genfa tersd dsad ",
time: "10:00 AM",
}
],
},
{
day: 13,
month: 11,
year: 2022,
events: [
{
title: "Event 2",
time: "11:00 AM",
},
],
},
];
The format is am being able to produce is the following.
const eventsArr = [
{
"day": "18",
"month": "2",
"year": "2023",
"events": [
{
"title": "Feb 18th Event and Updated From Databae",
"time": "05:10"
}
]
}
The Only difference between two javascript objects/arrays is that my version has "" around the keys and the working format does not have "" around the keys.
My Server Side PHP Code where i am using json_encode
$events = [];
foreach($db_data['CalendarEvent'] as $event)
{
$single_event = array(
'day'=>$event->ce_day,
'month'=>$event->ce_month,
'year'=>$event->ce_year,
'events'=>array(
array(
'title'=> $event->ce_title,
'time'=> $event->ce_time_from,
)
)
);
$events[] = $single_event;
}
$db_data['all_events'] = json_encode($events , JSON_PRETTY_PRINT);
Can somebody help me in this? How can i produce the required format (without "" around the keys in javascript). What i am doing wrong?
Thanks in Advance
How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks
var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
let obj = {[author: [], book: [], condition: [], status: [], date: []]}
for(let x = 0; x < data.length; x++){
obj.author.push(data[x][0]);
obj.book.push(data[x][1]);
obj.condition.push(data[x][2]);
obj.status.push(data[x][3]);
obj.date.push(data[x][4]);
}
console.log("obj: ", obj)
return resolve(obj);
})
The Current result of console.log("obj: ", obj)
{
"authors": "testuser,testname",
"books": "440936785,440936694",
"conditions": "Very Good,New,",
"status": "Not Available,Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
What I want result:
{
"authors": "testname",
"books": "440936694",
"conditions": "New",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:24 GMT+0800 (Philippine Standard Time)"
},
{
"authors": "testname",
"books": "440936694",
"conditions": "New,",
"status": "Available",
"datepublished": "Mon Mar 28 2022 18:42:39 GMT+0800 (Philippine Standard Time)"
}
You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:
const objects = data.map(row => ({
author: row[0],
book: row[1],
condition: row[2],
status: row[3],
date: row[4],
}));
The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.
I have to do something like left join in sql in node with JSON data. Actually, on componentWillReceiveProps react (if it's changing anything).
my state:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": [],
"2017-11-12": [],
"2017-11-13": []
}
my data to join:
const visit = {
"2017-11-11": "10:30",
"2017-11-12": "10:00",
"2017-11-12": "10:30"
}
And in componentdidmount i need to setState so that as result get that:
const dayList = {
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": [],
"2017-11-11": ["10:30"],
"2017-11-12": ["10:00","10:30"],
"2017-11-13": []
}
I know how to achieve it with .map, and another loop inside with if statement. But I am sure that there is a better approach.
What may you suggest?
Yes, actually you are right. I answered the wrong question. Is not a valid JSON neither.
But still, there is a case to do.
My very raw data from db looks like that:
[
{
"createDate": "Tue Nov 07 2017 20:56:27 GMT+0100",
"visitDate": "20171110",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 20:56:36 GMT+0100",
"visitDate": "20171111",
"visitTime": "1000",
"doctor": {
"name": "name1"
}
},
{
"createDate": "Tue Nov 07 2017 23:30:03 GMT+0100",
"visitDate": "20171111",
"visitTime": "1030",
"doctor": {
"name": "name1"
}
}
];
and in react component and need to display it as a list of visits per day like that
"2017-11-08": [],
"2017-11-09": [],
"2017-11-10": ["10:30"],
"2017-11-11": ["10:00","10:30"],
"2017-11-12": []
"2017-11-13": []
Is there quick way to filter an array of objects to return only a few properties in each object?
For example we have the data below:
var objArr = [{
"Title": "July 13 - July 19 2014",
"displayAd_imp": "3,500",
"videoAd_imp": "1.5",
"tv_imp": "0.52",
"Date": "2014-07-17T00:00:00.000Z",
"WeekNo": 29
}, {
"Title": "July 20 - July 26 2014",
"displayAd_imp": "1,600",
"videoAd_imp": "2.55",
"tv_imp": "0.052",
"Date": "2014-07-24T00:00:00.000Z",
"WeekNo": 30
}, {
"Title": "July 27 - Aug 2 2014",
"displayAd_imp": "1,500",
"videoAd_imp": "2.1",
"tv_imp": "0.122",
"Date": "2014-07-31T00:00:00.000Z",
"WeekNo": 31
}]
I'm trying to filter the array above to get another array with only videoAd_imp, videoAd_imp, tv_imp. so it would look like this:
[{
"displayAd_imp": "3,500",
"videoAd_imp": "1.5",
"tv_imp": "0.52",
}, {
"displayAd_imp": "1,600",
"videoAd_imp": "2.55",
"tv_imp": "0.052",
}, {
"displayAd_imp": "1,500",
"videoAd_imp": "2.1",
"tv_imp": "0.122",
}]
Thanks in advance!
Use Array.map like bellow
If you want new references to all objects.
var newArr = objArr.map(function (obj) {
return {displayAd_imp:obj.displayAd_imp,videoAd_imp:obj.videoAd_imp,tv_imp:obj.tv_imp};
})
console.log(newArr);
If you want to get original references use like bellow
var newArr = objArr.map(function (obj) {
delete obj.Date;
delete obj.WeekNo;
delete obj.Title
return obj;
})
var objArr = [{/* ... */}];
// cache the array length to avoid resolving it on every iteration
var arrLength = objArr.length;
// your new array
var newArr = [];
for(var i=0; i<arrLength; i++){
// push only the properties you want to the new array
newArr.push({
displayAd_imp: objArr[i].displayAd_imp,
videoAd_imp: objArr[i].videoAd_imp,
tv_imp: objArr[i].tv_imp
});
}
// show it in the console
console.log(newArr);
JS Fiddle Demo
Here is a simple solution
var newArr = []
for(var i=0;i<objArr.length) {
newArr.push({
displayAd_imp: objArr[i].displayAd_imp,
videoAd_imp: objArr[i].videoAd_imp,
tv_imp: objArr[i].tv_imp
}
);
}
My json is:
[
{
"_id":{
"time":1381823399000,
"new":false,
"timeSecond":1381823399,
"machine":263168773,
"inc":-649466399
},
"asset":"RO2550AS1",
"Salt Rejection":"90%",
"Salt Passage":"10%",
"Recovery":"59%",
"Concentration Factor":"2.43",
"status":"critical",
"Flow Alarm":"High Flow"
},
[
{
"Estimated Cost":"USD 15",
"AssetName":"RO2500AS1",
"Description":"Pump Maintenance",
"Index":"1",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO2500AS1",
"Description":"Heat Sensor",
"Index":"2",
"Type":"Replacement",
"DeadLine":"26 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO2550AS1",
"Description":"Heat Sensor",
"Index":"3",
"Type":"Replacement",
"DeadLine":"26 November 2013"
},
{
"Estimated Cost":"USD 15",
"AssetName":"RO2550AS1",
"Description":"Pump Maintenance",
"Index":"4",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 15",
"AssetName":"RO3000AS1",
"Description":"Pump Maintenance",
"Index":"5",
"Type":"Service",
"DeadLine":"13 November 2013"
},
{
"Estimated Cost":"USD 35",
"AssetName":"RO3000AS1",
"Description":"Heat Sensor",
"Index":"6",
"Type":"Replacement",
"DeadLine":"26 November 2013"
}
]
]
I need to access it in javascript.
The following code is not working:
var jsonobjstr = JSON.parse(jsonOutput);
alert ("asset: "+jsonobjstr.asset);
Because the entire JSON is contained in an array.
alert("asset: "+jsonobjstr[0].asset);
http://jsfiddle.net/ExplosionPIlls/yHj5X/2/
In javascript
var somename = []; means a new array and;
var somename = {}; means a new object.
Therefore if some json starts with a [] means it is a array of objects, and if it starts with {} means it is a object.
Your json starts with [], therefore it is a array of objects, so you need to access each object by doing:
json[n].asset for each position of the array (where n is a integer).
BUT:
Your JSON is weird. Looks like you will always have a array with one element (if true, the json should start with {}.
LIKE:
{
"id":
{
"code":1381823399000
},
"asset":"RO2550AS1",
"history":
[
{
"value":"USD 15"
},
{
"value":"USD 15"
},
{
"value":"USD 15"
}
]
}
Here you can do:
thing.id.code
thing.asset
thing.history[0].value
thing.history[1].value