Object returning NaN when sum values - javascript

I'll admit I'm weak in JavaScript and JSON. I've spent a lot of time attempting to figure out why numbers from my objects returns NaN when they are added together. With that in mind, below is my JSON, stored to a variable:
var data = [
{
"acc_ext_id": null,
"cat_code": 10002,
"cat_ds": "REVENUE",
"category_id": null,
"chart_id": null,
"created_at": null,
"dept_id": null,
"feb": null,
"id": null,
"jan": 30,
"note": null,
"total_cost": null,
"updated_at": null,
"year_id": null
},
{
"acc_ext_id": "41260-02600",
"cat_code": 10002,
"cat_ds": "REVENUE",
"category_id": 2,
"chart_id": 2373,
"created_at": "2013-01-15 16:43:52.169213",
"dept_id": 86,
"feb": 45,
"id": 3,
"jan": 60,
"note": "Two",
"total_cost": 105,
"updated_at": "2013-01-15 16:43:52.169213",
"year_id": 1
}
]
I then attempt to iterate over the objects and sum the values:
var jan;
for (var i=0;i<data.length;i++){
if(data[i].jan != null){
jan += parseFloat(data[i].jan);
console.log(jan);
}
}
Printed out in the console is NaN. I've attempted to parse the number as well as leave it raw, but to no avail. Is there something wrong with my objects? Here is a jsFiddle to illustrate: http://jsfiddle.net/5E2pm/3/

var jan = 0; //this should solve it
for (var i=0;i<data.length;i++){
if(data[i].jan != null){
jan += parseFloat(data[i].jan);
console.log(jan);
}
}
Try this should solve it :)
Explanation as quoted by DON in comments below:
var jan; this will declare variable as undefined, so when you try to
add values with undefined you will get as NaN, so the answer here with
var jan = 0 will work – DON

2021
This is a good use for a reducer
const jan = data.reduce(function(total, current) {
return total + current.jan;
}, 0); // starting value
OLD ANSWER
I like this approach. It basically sets the value to 0 on the first iteration when jan doesn't exist.
jan = (jan || 0) + parseFloat(data[i].jan);

you need to initialize jan first
var jan = 0;
here's the example - link

Related

Why does this delete information from both jsons

I try to delete information from a JSON but when i put the og JSON to a new variable and then delete some of the information from both
example:
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
so this code should from what i know that it will asign a new JSON and then delete the members from newJSONFile and keep the members in the originalJSON but when i console.log(originalJSON) it output the members to be empty and i dont understand why
What looks like is your newJSONFile and originalJSON are both the same.
The objects in JS, they refer to same location. Unlike primitives we cant make a copy simply by using =. You can read more about it here
We can create deep copies using spread and other ways const newJSONFile = {...originalJSON} but this will still not deep copy the nested objects.
I am not aware of the structure your JSON is so can't suggest best way to create a deep copy.
You can use clone functions from libraries like lodash
UPDATED:
Create a deep clone of your original JSON, instead of just creating a reference. Then you can delete from the clone, and retain the original:
/* YOUR JSON FILE */
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
/* LOG OG JSON FILE */
console.log(newJSON);
/* DEEP CLONE JSON FILE - MAKES A COPY */
let deepCloneJSON = JSON.parse(JSON.stringify(newJSON));
/* DELETE FROM THE COPY, NOT THE ORIGINAL */
delete deepCloneJSON.members[1];
console.log(deepCloneJSON);
/* CHECK THE ORIGNAL IS STILL INTACT */
console.log(newJSON);
https://jsfiddle.net/pixelmedia/7j18y5sp/12/
Old responses due to vague question:
Your question seems rather confusing, but if you are trying to delete from your JSON, then use the following.
Example: This will delete the second, and leave the first (0).
delete originalJSON[1];
Another example:
Initial is: 1, 2, 3
const originalJSON = [1, 2, 3];
delete originalJSON[1];
console.log(originalJSON);
Expected output: 1, 3
Now updated to demonstrate with the additional information provided by the OP:
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
delete newJSON.members[1];
console.log(newJSON);
Expected output: removed 'Tinyruthless'
JSFiddle: https://jsfiddle.net/pixelmedia/7j18y5sp/1/
so my json will look like this:
{
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
and i want to make it so that i can go through it and then delete one of the members and keep the rest in the same order
so i thought that i could just do
console.log(`deleteing person`)
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
for(m in originalJSON.members) {
console.log(`for loop runs`)
if(originalJSON.members[m]['name'] !== args[0]) {
let addMember = {
"name": originalJSON.members[m]['name'],
"instagram": originalJSON.members[m]['instagram'],
"signupDate": originalJSON.members[m]['signupDate']
}
newJSONFile.members.push(addMember)
console.log(newJSONFile)
}else {
}
}
and it just deletes it from both
Hi I used below script for this scenario.
const orgObj = { foo: "foo", bar: [1, 2, 3] }
var clonedObj = Object.assign({}, orgObj);
clonedObj.bar = Array.from(clonedObj.bar);
clonedObj.bar.push(4);
console.log(orgObj)
console.log(clonedObj)
It will make complete saperate copy of you object and OrgObj will remain unchanged.

Google Sheets: API returning undefined for json tag

I've been trying to use an online API (albion-online-data.com) for a while in sheets, creating a little function to try to grab a specific identifier, sell_price_min, but the function keeps returning undefined.
I've been looking around for ages but haven't been able to find out what's wrong. Sorry, I'm new to APIs and google sheets in general. I used Logger.log, and it shows the correct contents after Json.parse, but when trying to use
return w.sell_price_min;
it always returns undefined.
Here's the code:
/**
* Retrieve the current price for a given city.
*
*/
function CURRENTPRICE(name, location, quality) {
name = encodeURI(name);
location = encodeURI(location);
quality = encodeURI(quality);
var response = UrlFetchApp.fetch("http://www.albion-online-data.com/api/v2/stats/Prices/" + name + "?locations=" + location + "&qualities=" + quality);
var w = JSON.parse(response.getContentText());
return w.sell_price_min;
}
and the API is:
https://www.albion-online-data.com/api/v2/stats/prices/T4_BAG,T5_BAG?locations=Caerleon,Bridgewatch&qualities=2
which returns the following: (reformatted here with indentation and line breaks for readability)
[
{
"item_id": "T4_BAG",
"city": "Bridgewatch",
"quality": 2,
"sell_price_min": 4000,
"sell_price_min_date": "2019-09-02T22:20:00",
"sell_price_max": 4444,
"sell_price_max_date": "2019-09-02T22:20:00",
"buy_price_min": 0,
"buy_price_min_date": "0001-01-01T00:00:00",
"buy_price_max": 0,
"buy_price_max_date": "0001-01-01T00:00:00"
},
{
"item_id": "T4_BAG",
"city": "Caerleon",
"quality": 2,
"sell_price_min": 5571,
"sell_price_min_date": "2019-09-03T11:05:00",
"sell_price_max": 5571,
"sell_price_max_date": "2019-09-03T11:05:00",
"buy_price_min": 2375,
"buy_price_min_date": "2019-09-03T08:41:00",
"buy_price_max": 4020,
"buy_price_max_date": "2019-09-03T08:41:00"
},
{
"item_id": "T5_BAG",
"city": "Bridgewatch",
"quality": 0,
"sell_price_min": 20000,
"sell_price_min_date": "2019-09-01T14:00:00",
"sell_price_max": 22100,
"sell_price_max_date": "2019-09-01T14:00:00",
"buy_price_min": 0,
"buy_price_min_date": "0001-01-01T00:00:00",
"buy_price_max": 0,
"buy_price_max_date": "0001-01-01T00:00:00"
},
{
"item_id": "T5_BAG",
"city": "Caerleon",
"quality": 2,
"sell_price_min": 23897,
"sell_price_min_date": "2019-09-03T11:03:00",
"sell_price_max": 26376,
"sell_price_max_date": "2019-09-03T11:03:00",
"buy_price_min": 15000,
"buy_price_min_date": "2019-09-02T22:21:00",
"buy_price_max": 22550,
"buy_price_max_date": "2019-09-02T22:21:00"
}
]
and the results should be: 4000?
Sorry for any hassle... I've been stumped for literally hours .-.
You are accessing a JSON array. So it should be
for(var i = 0; i < w.length; i++) {
var obj = w[i];
console.log(obj.sell_price_min);
}
If you want to get the first value of the array put
return w[0].sell_price_min

How can I check if a variable in an array in an array in an array is defined and not null?

I am trying to check to see if wordDefinitionId is defined and not null. Here's what I have been trying to do but think even this code seems to give some problems. Is there an easy way for me to do this check and set the value of wos.wordDefinitionId to either the value (if it exists) or zero if it does not exist.
if (wos.word.wordForms) {
if (wos.word.wordForms[0].wordDefinitions) {
if (wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId
}
}
}
Note that if set then I want to get the wordDefinitionId that is in the first array position of wordDefinitions etc.
Update:
I tried the answer suggested:
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId;
if (wos.word.wordForms && wos.word.wordForms[0].synonyms && wos.word.wordForms[0].synonyms[0].synonymId)
wos.synonymId = wos.word.wordForms[0].synonyms[0].synonymId
// When I debug the code does not reach the next line.
if (wos.word.wordForms && wos.word.wordForms[0].sampleSentences && wos.word.wordForms[0].sampleSentences[0].sampleSentenceId)
wos.sampleSentenceId = wos.word.wordForms[0].sampleSentences[0].sampleSentenceId
However when I debug the code does not reach the final "if"
Here for reference are the objects:
console.log(JSON.stringify(wos.word))
VM6085:1 {"wordId":"tyyyyyy","wordIdentity":160,"ascii":116,"categoryId":1,"groupId":1,"lessonId":1,"ielts":null,"toefl":true,"toeic":null,"wordForms":[{"wordFormId":"qwqwqwqwq","wordFormIdentity":145,"ascii":113,"wordId":"tyyyyyy","primary":false,"posId":1,"sampleSentences":[],"synonyms":[],"wordDefinitions":[{"wordDefinitionId":142,"wordFormId":"qwqwqwqwq","text":"wrwrwrwrwr","ascii":119}],"pos":null,"version":"AAAAAAAADn0=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z"}],"lesson":null,"wordCategory":null,"wordGroup":null,"version":"AAAAAAAADf4=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z","current":true}
Same here but maybe easier to see:
console.log(JSON.stringify(wos.word))
VM6085:1 {"wordId":"tyyyyyy","wordIdentity":160,"ascii":116,"categoryId":1,"groupId":1,"lessonId":1,"ielts":null,"toefl":true,"toeic":null,"wordForms":[{"wordFormId":"qwqwqwqwq","wordFormIdentity":145,"ascii":113,"wordId":"tyyyyyy","primary":false,"posId":1,"sampleSentences":[],"synonyms":[],"wordDefinitions":[{"wordDefinitionId":142,"wordFormId":"qwqwqwqwq","text":"wrwrwrwrwr","ascii":119}],"pos":null,"version":"AAAAAAAADn0=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z"}],"lesson":null,"wordCategory":null,"wordGroup":null,"version":"AAAAAAAADf4=","createdBy":2,"createdDate":"2016-05-03T13:23Z","modifiedBy":2,"modifiedDate":"2016-05-03T20:23Z","current":true}
Use &&(AND) logical operator between conditions, if first condition fails second condition will not check and so on
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId
var wos = {
word: {
"wordId": "tyyyyyy",
"wordIdentity": 160,
"ascii": 116,
"categoryId": 1,
"groupId": 1,
"lessonId": 1,
"ielts": null,
"toefl": true,
"toeic": null,
"wordForms": [{
"wordFormId": "qwqwqwqwq",
"wordFormIdentity": 145,
"ascii": 113,
"wordId": "tyyyyyy",
"primary": false,
"posId": 1,
"sampleSentences": [],
"synonyms": [],
"wordDefinitions": [{
"wordDefinitionId": 142,
"wordFormId": "qwqwqwqwq",
"text": "wrwrwrwrwr",
"ascii": 119
}],
"pos": null,
"version": "AAAAAAAADn0=",
"createdBy": 2,
"createdDate": "2016-05-03T13:23Z",
"modifiedBy": 2,
"modifiedDate": "2016-05-03T20:23Z"
}],
"lesson": null,
"wordCategory": null,
"wordGroup": null,
"version": "AAAAAAAADf4=",
"createdBy": 2,
"createdDate": "2016-05-03T13:23Z",
"modifiedBy": 2,
"modifiedDate": "2016-05-03T20:23Z",
"current": true
}
};
if (wos.word.wordForms && wos.word.wordForms[0].wordDefinitions && wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId)
wos.wordDefinitionId = wos.word.wordForms[0].wordDefinitions[0].wordDefinitionId
document.write('<pre>' + JSON.stringify(wos, 0, 3) + '</pre>');
You don't reach the third if, because in your second if statement, the wos.word.wordForms[0].synonyms will evaluate to true as it is defined and is an empty list. You can check it yourself:
if (wos.word.wordForms[0].synonyms) { alert('Yes!'); } // will alert 'Yes!'
But right next to it, you try to access wos.word.wordForms[0].synonyms[0], which does not exist, hence the TypeError: wos.word.wordForms[0].synonyms[0] is undefined. The same situation is with your wos.word.wordForms[0].sampleSentences
In order to fix this, check the length of the list as well:
if (wos.word.wordForms
&& wos.word.wordForms[0].synonyms
&& wos.word.wordForms[0].synonyms.length // <-- check for element existence
&& wos.word.wordForms[0].synonyms[0].synonymId) {
...
}

getting information from the inner depths of a JSON object

I have a JSON object from the CrunchBase API giving me a bunch of info from a given company. Right now I am trying to go through the JSON object and create a list of their investors. The investors can fall into one of three categories, "company", "financial_org", or "person". All three types will be appended to the same list, finalInvestorList
The script runs without error, but only produces a list of investors from the first listed round. I have logged everything I think might help. the logs are in same-line comments.
Basically my problem is that it is only looping through one time, and therefor only adding the investors from the first round. Any help would be greatly appreciated. Let me know if you need more info!
var investorList = function(data, num) {
var fundingRounds = data["funding_rounds"];
var finalInvestorList = []
console.log(fundingRounds.length) // 3
for (i=0; i < fundingRounds.length; i++) {
var investments = data["funding_rounds"][i]["investments"];
console.log(data["funding_rounds"][1]["investments"]); //correctly logs the index 1 round for spling (2nd round)
var round = data["funding_rounds"][i];
console.log('round' + i); //only logs round0, never loops around for round1, round2
for (i=0; i < investments.length; i++) {
var angelObject = round["investments"][i]["person"];
if (angelObject != null) {
console.log("angel fired"); //fires for "Mitch Blumenfeld"
var angel = angelObject["first_name"] + " " + angelObject["last_name"];
finalInvestorList[i] = angel;
}
var financialOrgObject = round["investments"][i]["financial_org"];
if (financialOrgObject != null) {
console.log("financial_org fired"); //fires for "Bucknell Venture Plan Competition"
console.log(financialOrgObject['name']); //Bucknell VPC
var financialOrg = financialOrgObject["name"]
finalInvestorList[i] = financialOrg
}
var companyObject = round['investments'][i]["company"];
if (companyObject != null) {
console.log('company fired'); //i haven't bothered with this yet.. just logging it so ill know if its firing
}
}
}
console.log(finalInvestorList); //["Bucknell Venture Plan Competition", "Mitch Blumenfeld"]
}
The JSON object represented by the data is as follows
I have shortened it with just the bit needed. The object inside the JSON response data is represented by data["funding_rounds"]
this data was retrieved using the crunch API and can be found in full form at http://api.crunchbase.com/v/1/company/spling.js
"funding_rounds":
[{"round_code": "seed",
"source_url": "",
"source_description": "",
"raised_amount": 50000.0,
"raised_currency_code": "USD",
"funded_year": 2011,
"funded_month": 2,
"funded_day": 1,
"investments":
[{"company": null,
"financial_org":
{"name": "Bucknell Venture Plan Competition",
"permalink": "bucknell-venture-plan-competition",
"image": null},
"person": null},
{"company": null,
"financial_org": null,
"person":
{"first_name": "Mitch",
"last_name": "Blumenfeld",
"permalink": "mitch-blumenfeld",
"image": null}}]},
{"round_code": "seed",
"source_url": "http://techcrunch.com/2011/09/08/dreamit-ventures-launches-its-fall-2011-philadelphia-class/",
"source_description": "",
"raised_amount": 25000.0,
"raised_currency_code": "USD",
"funded_year": 2011,
"funded_month": 9,
"funded_day": 1,
"investments":
[{"company": null,
"financial_org":
{"name": "DreamIt Ventures",
"permalink": "dreamit-ventures",
"image":
{"available_sizes":
[[[150,
57],
"assets/images/resized/0002/7773/27773v5-max-150x150.jpg"],
[[250,
96],
"assets/images/resized/0002/7773/27773v5-max-250x250.jpg"],
[[251,
97],
"assets/images/resized/0002/7773/27773v5-max-450x450.jpg"]],
"attribution": null}},
"person": null}]},
{"round_code": "a",
"source_url": "http://techcrunch.com/2011/12/05/new-content-sharing-network-spling-launches-announces-400k-series-a/",
"source_description": "New Content Sharing Network Spling Launches, Announces $400K Series A",
"raised_amount": 400000.0,
"raised_currency_code": "USD",
"funded_year": 2011,
"funded_month": 12,
"funded_day": 5,
"investments":
[{"company": null,
"financial_org":
{"name": "Deep Fork Capital",
"permalink": "deep-fork-capital-2",
"image":
{"available_sizes":
[[[150,
20],
"assets/images/resized/0008/0167/80167v1-max-150x150.png"],
[[250,
34],
"assets/images/resized/0008/0167/80167v1-max-250x250.png"],
[[450,
62],
"assets/images/resized/0008/0167/80167v1-max-450x450.png"]],
"attribution": null}},
"person": null},
{"company": null,
"financial_org": null,
"person":
{"first_name": "John",
"last_name": "Ason",
"permalink": "john-ason",
"image": null}},
{"company": null,
"financial_org": null,
"person":
{"first_name": "Mitchell",
"last_name": "Blumenfeld",
"permalink": "mitchell-blumenfeld",
"image": null}},
{"company": null,
"financial_org": null,
"person":
{"first_name": "Gianni",
"last_name": "Martire",
"permalink": "gianni-martire",
"image":
{"available_sizes":
[[[138,
150],
"assets/images/resized/0006/3720/63720v4-max-150x150.jpg"],
[[230,
250],
"assets/images/resized/0006/3720/63720v4-max-250x250.jpg"],
[[414,
450],
"assets/images/resized/0006/3720/63720v4-max-450x450.jpg"]],
"attribution": ""}}}]}]
Thanks for the help!
You are using the same variable name for the counter in each loop, so when the inner loop completes and the outer loop gets to its second iteration, i is investments.length, not 1. Use different variable names for each loop:
for (var roundIdx = 0; roundIdx < fundingRounds.length; roundIdx++) {
...
for (var invIdx = 0; invIdx < investments.length; invIdx++) {
...
Also, don't populate your array using array[i] = value notation, just use array.push(value). You don't need to keep track of the indexes.
But, I'd recommend iterating your arrays using Array.forEach() and using dot syntax instead of square bracket notation:
function investorList(data, num) {
var finalInvestorList = [];
data.funding_rounds.forEach(function (round, i) {
round.investments.forEach(function (investment, i) {
if (investment.person) {
finalInvestorList.push(investment.person.first_name + " " +
investment.person.last_name);
}
else if (investment.financial_org) {
finalInvestorList.push(investment.financial_org.name)
}
else if (investment.company) {
finalInvestorList.push(investment.company.name)
}
}
}
}
For older browsers that don't natively support Array.forEach(), use the implementation here to shim the browser.

Parsing JSON with jQuery, retrieving two variables.

I have a online JSON file that looks something like this:
[
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
"TravelStages": [
{
"ID": 0,
"DepartureStop": {
"WalkingDistance": 0,
"ArrivalTime": null,
"AlightingAllowed": false,
"DepartureTime": null,
"BoardingAllowed": false,
"RealTimeStop": true,
"Rank": 0,
"Lines": null,
"StopPoints": [
{
"ID": 1,
"Name": "1",
"X": 608127,
"Y": 6645778
}
],
"Zone": "1",
"X": 608133,
"Y": 6645768,
"ID": 2300500,
"Name": "Visperud (i Solheimvn)",
"District": "Lørenskog",
"Type": 0,
"Stops": [],
"ShortName": "VIS"
}]
What I want is the grab out the DepartureTime and ArrivalTime, I've seen some examples on how to parse the flickr JSON. But I can't figure out how I can parse this. I also want to store the departureTime and arrivalTime in two separate variables since the content of this two is a time measured in milliseconds since 1970. Can somebody give me a hint on how a can do this, am totally new to Javascript/JSON
Do you have jQuery in your project? If so, you can easily parse the JSON string like this
var obj = $.parseJSON(theJsonText);
alert(obj.DepartureTime);
If not, I suggest including the JSON library (link) and using that.
You can try something like this, assuming that your json file is in jsonfile.json
$.getJSON('jsonfile.json', function(data){
alert("Departure Time: "+ data.DepartureTime);
alert("Arrival Time: "+ data.ArrivalTime);
});
http://api.jquery.com/jQuery.getJSON/
$.getJSON('http://your.domain.example/path/to/file.json', function(data) {
departure_time=data.DepartureTime;
arrival_time=data.ArrivalTime;
do_something_with(departure_time,arrival_time);
});
then do_something_with(str,str) would be called with the strings "\/Date(1331667480000+0100)\/" and "\/Date(1331668860000+0100)\/" (in your example).
you'll still have to convert the dates to numbers, e.g. by running:
parsed_date=new Date(parseInt(input_string.substr(7)));
//substr(7) cuts after "\/Date(", and parseInt ignores ")\/"
//but I don't know how it handles "+0100"
Thats an array containing objects, so you should be able to just set some vars equal to the properties of the first index. to use it like an object, it needs to be parsed.. so either eval(thatJson) or $.parseJSON(thatJson) and then iterate through it.
var responses = [
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
...
}];
var dep = responses[0].DepartureTime;
var arr = responses[0].ArrivalTime;
According to JSONLint.com, your string isn't valid JSON. That is, however, a different issue than what your question asks for.
Assuming a valid subset of your string
var a = '[{"j": 0,"i": 0,"DepartureTime": "/Date(1331667480000+0100)/", "ArrivalTime": "/Date(1331668860000+0100)/","Remarks": []}]';
var obj = $.parseJSON(a);
console.log(obj[0].ArrivalTime);​

Categories

Resources