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.
Related
I have an array of objects that looks like this:
[
{
"id": 123,
"timeStamp": "\"2019-07-08T20:36:41.580Z\"",
"data": [1, 2, 3]
},
{
"id": 234,
"timeStamp": "\"2019-07-08T20:37:12.472Z\"",
"data": ["Apples", "Oranges"]
}
]
I want to update the value of a particular property of an object within the array but also want to make sure that I return the result in a new array.
How do I do this without running through some type of a loop e.g. for loop?
Say, I want to update the data property of the second object and add Bananas to it.
If you want the result to be a new array, you'll first have to clone the array. This can be more complicated than you might imagine (depending on how deeply you wish to clone things). One way is to use JSON stringify...
Bear in mind that the JSON trick is effectively doing a loop behind the scenes. Inevitable if you want to copy the array, really.
To find the object by ID use Array.find()
let original = [
{
"id": 123,
"timeStamp": "\"2019-07-08T20:36:41.580Z\"",
"data": [1, 2, 3]
},
{
"id": 234,
"timeStamp": "\"2019-07-08T20:37:12.472Z\"",
"data": ["Apples", "Oranges"]
}
]
let copy = JSON.parse(JSON.stringify(original));
copy.find(obj => obj.id === 234).data.push("Bananas");
console.log(copy);
Something like this would do the trick:
let arr = [
{
"id": 123,
"timeStamp": "\"2019-07-08T20:36:41.580Z\"",
"data": [1, 2, 3]
},
{
"id": 234,
"timeStamp": "\"2019-07-08T20:37:12.472Z\"",
"data": ["Apples", "Oranges"]
}
]
arr[1]['data'] = [...arr[1]['data'], 'Bananas']
console.log(arr)
For your example: you can do something like this: say your array of object is saved in test variable
test[1].data.push("Bananas")
I'm asking here as I can see this website the most one can help in this
I have an output value in JASON format as the following:
{
"total": 16,
"members": [{
"id": 4,
"name": "Blade11",
"descriptors": {
"os": "Windows 2012 / WS2012 R2"
},
"FCPaths": [{
"wwn": "50060B0000C27208",
"hostSpeed": 0
}, {
"wwn": "50060B0000C2720A",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 11,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 11\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}, {
"id": 6,
"name": "Blade4",
"descriptors": {
"os": "VMware (ESXi)"
},
"FCPaths": [{
"wwn": "50060B0000C27216",
"hostSpeed": 0
}, {
"wwn": "50060B0000C27214",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 8,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 8\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}
what I want is, to parse this output for retrieving an output parameter with the name object only in a list or array of string
for example Names = Blade11, Blade4,....
if you can see in the Json output we have all the names under "members", then each one is another array of values, I want to retrieve only names
thanks
If this JSON is string first you have to parse it
var json = JSON.parse('here is your JSON string');
Than you can access to it properties like you work with object
var names = json.members.map(function(member) {
return member.name;
});
Since you already have JSON format, you can use an array method on the member key of your JSON object to iterate through each array item.
var names = [];
object_name.members.forEach((arrItem) => {
names.push(arrItem.name);
}
or
namesArray = object_name.members.map((arrItem) => {
return arrItem.name;
}
You could use Array#map for iterating all elements of the array and return only the name property.
If you have a JSON string, you need to parse it in advance for getting an object, like
object = JSON.parse(jsonString);
var jsonString = '{"total":16,"members":[{"id":4,"name":"Blade11","descriptors":{"os":"Windows 2012 / WS2012 R2"},"FCPaths":[{"wwn":"50060B0000C27208","hostSpeed":0},{"wwn":"50060B0000C2720A","hostSpeed":0}],"iSCSIPaths":[],"persona":11,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 11\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false},{"id":6,"name":"Blade4","descriptors":{"os":"VMware (ESXi)"},"FCPaths":[{"wwn":"50060B0000C27216","hostSpeed":0},{"wwn":"50060B0000C27214","hostSpeed":0}],"iSCSIPaths":[],"persona":8,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 8\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false}]}',
object = JSON.parse(jsonString),
array = object.members.map(function (a) { return a.name; });
console.log(array);
I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);
I'm hitting an api built using CakePHP. Cake returns its objects like this:
[
{
"Note": {
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
}
},
{
"Note": {
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
}
]
What I want to do is take that result and basically get rid of the keys. Something like this:
[
{
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
},
{
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
]
I'm basically just trying to make it easier to reference this in Angular. I need to do this on the client side. Any ideas?
You could refactor it like so:
var json = '[{"Note":{"id":"1","clas":"test","obj_id":null,"note":"test"}},{"Note":{"id":"2","clas":"another","obj_id":null,"note":"another"}}]';
var obj = JSON.parse(json);
var arr = [];
for (i = 0; i < obj.length; i++)
{
arr.push(obj[i].Note);
}
Working example here
(Note also that if your key value 'Note' isn't always the same, this will change dramatically. It's likely that 'Note' isn't going to be the same in each instance either; that would generate an improperly keyed object. Alternatively, if you always need the first object in the array, you could use obj[i][0] instead).
(More note if you're using cakephp, this would be much easier done using Hash::, but if you need to do it client side, this is the solution).
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);