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);
Related
I have a site in which there is a <script> with a JSON inside. With user script in Tampermonkey, I want to get that JSON to work with it later.
So I thought that I can get it with getElemntsByTagName("script"), but I couldn't figure out how to get string out of it.
How do you get a string from getElemntsByTagName("script"), like console.log does?
Is there an easier way to do so?
window.wpProQuizInitList = window.wpProQuizInitList || [];
window.wpProQuizInitList.push({
id: '#wpProQuiz_67',
init: {
quizId: 67,
mode: 2,
globalPoints: 76,
timelimit: 0,
resultsGrade: [0],
bo: 3,
qpp: 0,
catPoints: [76],
formPos: 0,
lbn: "\u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u0438 \u0442\u0435\u0441\u0442",
json: {
"2944": {
"type": "single",
"id": 2944,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
"2945": {
"type": "single",
"id": 2945,
"catId": 0,
"points": 1,
"correct": [0,1,0,0]
},
"2946": {
"type": "single",
"id": 2946,
"catId": 0,
"points": 1,
"correct": [0,0,1,0]
},
…
}
}
}
You can use document.querySelector to get the first <script> element; there is no need to obtain a live HTMLCollection to get one element. You can then read its textContent.
let value = document.querySelector('script').textContent;
getElementsByTagName("script") will return an HTMLCollection which contains a list of script tags. You can get the text of the first script tag like this:
getElementsByTagName("script")[0].innerText
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle
when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.
How to get value from [object Object] in javaScript.
i have a json response from php which i pass in javascript .
i want GPSPoint_lat,GPSPoint_lon all value.
var jArray = ;
var obj = JSON.parse(jArray);
i got [object Object] how i retrive the all value from obj.
my json string is-
{
"Account": "dimts",
"Account_desc": "Adminstrator",
"TimeZone": "Asia/Calcutta",
"DeviceList": [
{
"Device": "dl1pb1831",
"Device_desc": "DL 1PB 1831",
"EventData": [
{
"Device": "dl1pb1831",
"Timestamp": 1387790572,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:52",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.52802,77.14041",
"GPSPoint_lat": 28.52802,
"GPSPoint_lon": 77.14041,
"Speed": 12.9,
"Speed_units": "km/h",
"Heading": 193.6,
"Heading_desc": "S",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
{
"Device": "dl1pb7520",
"Device_desc": "DL 1PB 7520",
"EventData": [
{
"Device": "dl1pb7520",
"Timestamp": 1387790574,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:54",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.56589,77.05268",
"GPSPoint_lat": 28.56589,
"GPSPoint_lon": 77.05268,
"Speed": 29.9,
"Speed_units": "km/h",
"Heading": 91.4,
"Heading_desc": "E",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
Look at javascript tutorial
obj['key_name']
JSON objects work as an array. You can access to an element with a key:
obj['Account'] // returns dimts
obj.Account // works also
You should read some tutorial about it, like JSON: What It Is, How It Works, & How to Use It
Please retrive the value as
var jArray = <?php echo json_encode($_SESSION['return'] ); ?>;
var obj = JSON.parse(jArray);
var value=obj.Result;
I have zero experience in php so I don't know what's the resulting object from your first line of code. But assuming jArray is a json object with the structure defined in your question...you access its values as shown below...
jArray.Account;
jArray.DeviceList[0].Device; //access the device property of the first object in the DeviceList array
jArray.DeciveList[0].EventData.StatusCode;
Can I create an object dynamically from JSON?
This is one of some in array:
values: [{
"$type": "Entrance, DataModel",
"EntranceDeviceData": {
"$type": "DeviceData, DataModel",
"Watchdog": 0,
"Inputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Outputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Faults": {
"$type": "Int16[], mscorlib",
"$values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
"StandingCommand": 0
},
"Vehicle": null,
"NextStates": {
"$type": "System.Collections.Generic.List`1[[System.String, mscorlib]], mscorlib",
"$values": ["CarApproachingBarrier"]
},
"Repository": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"
},
"Direction": 0,
"Name": "Entrance",
"Position": "0,0,0,0",
}, {...another object...
}, {...another one...
}
]
This both JSON objects are different. Can I create an object (for every other JSON object) without knowing in advance it's properties? How can I do it?
(I heard something that it possible, but maybe I didn't understand well the person who said that).
What you gave as examples of JSON in your original code above is Javascript's way of defining literal objects. json1 and json2 already ARE javascript objects, no need to create them.
// original code from question
var json1 = {
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
};
As nnnnnn pointed out below JSON is most commonly used to refer to a STRING containing code formatted as above, that would be:
var json1_as_string = '{
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
}';
To get from such a String to an actual Javascript Object you would need to parse it:
var json1 = JSON.parse(json1_as_string);
the opposite direction (Javascript Object to String) is achieved by stringify:
var json1_as_string = JSON.stringify(json1);
see https://developer.mozilla.org/en-US/docs/Using_native_JSON
p.s.
It does seem strange that these two very different objects have the same "_id".
You've changed the question completely, and I'm trying to understand what you are asking.
This both JSON objects are different. Can I create an object (for
every other JSON object) without knowing in advance it's properties?
How can I do it?
Yes, in Javascript you can create objects without knowing their properties in advance. Javascript is not strongly typed, and it has no classes. So there's absolutely no problem
with having objects with different properties.