Array JSON in javascript - javascript

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

Related

Remove " " from keys when PHP associative array in parsed through json_encode

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 parse/filter data from JSON file in Javascript

Is there any way to parse/filter the data present in JSON file in a Javascript file.
Basically, I am calling JSON file into my local javascript. I am having trouble in reading specific data and printing.
Can anyone please help.
JSON file contains:
{
"Data": [
{
"name": "John",
"age": 30
},
{
"joined on":"Jan 2015",
"working on": "Automation",
}
]
}
I am trying to read the above JSON file as:
var jfile = require("./Example.json");
var test = JSON.parse(JSON.stringify(jfile))
console.log(test)
I get the output like this:
{ Data:
[ { name: 'John', age: 30 },
{ 'joined on': 'Jan 2015', 'working on': 'Automation' } ] }
From the above, I am interested in accessing/filtering out only one i.e. "name". I would like to print only the value "John" to the console.
I have tried to use the ".filter" method to the JSON.parse method but it throws me an error as:
JSON.parse(...).filter is not a function
Is there any way to perform this activity?
You can access it using . dot notation
var a = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
}
console.log(a.Data[0].name)
filter is an array method.
JSON.parse(...) will not give you an array. It will give you an object with a Data property. The value of that property is an array.
JSON.parse(...).Data.filter.
You can't just ignore parts of your data structure.
If you have multiple items in your array of different shapes, you can use this
Access the Data key with json.Data
map your array to transform its items into names
apply filter(Boolean) to take out those who are undefined
In your case you'll end up with an array containing only one name John
const getName = json => json.Data.map(x => x.name).filter(Boolean);
const json = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
};
console.log(getName(json));
Your JSON's main level is an object (not an array) and only arrays have .filter method.
So filter the array under Data key:
var test = JSON.parse(JSON.stringify(jfile)).Data.filter(/*something*/);
But better if you aren't re-parse JSON:
var test = jfile.Data.filter(/*something*/);
As Quentin mentioned in his comment, What is the use of below statement ?
var test = JSON.parse(JSON.stringify(jfile))
You can directly access the name property from the response.
Try this :
var obj = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation"
}
]
};
// Solution 1
console.log(obj.Data.map(item => item.name).filter(Boolean));
// Solution 2
console.log(obj.Data.filter(item => item.name).map(elem => elem.name));

JSON joining data in loop using JavaScript

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": []

Filter objects in Javascript

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
}
);
}

flattening json to csv format

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/

Categories