Accessing data from json in Angularjs - javascript

I have a JSON object Like this-
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "
[{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"w\",\"ansYesOrNo\":false,\"ansDetails\":\"\"},{\"question\":\"Q2\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"ed\",\"ansYesOrNo\":false,\"ansDetails\":\"\"}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
I need to access the 1st question of questions.Please i am not able to access it like this alert(obj.questions[0].question);
Here is a jsFiddle Link-LINK to Fiddle

The main problem is that the questions array inside the object, It is not an array. Is a Array convert to string, you must parse the questions to get the respective Json object with the data.
Here is your fiddle updated: http://jsfiddle.net/marduke182/w02ck9uw/1/
And the part of code important:
var questonObj = JSON.parse($scope.a[0].questions);

Use fromJson method this way:
angular.fromJson(a[0].questions)[0].question

Related

How to get a value from nested JSON data

I am trying to get a value from the nested JSON data below. Specifically, the payments captures id value 0TA12948FV40723B is the value I need.
I try using the following codes to retrieve the value.
details.purchase_units.payments.captures.id
details.purchase_units.payments[0].captures.id
But I keep getting a console.log Error: "Order could not be captured"
JSON DATA
{
"create_time":"2019-02-19T05:06:52Z",
"update_time":"2019-02-19T05:06:52Z",
"id":"3HB96413YD922272B",
"intent":"CAPTURE",
"status":"COMPLETED",
"payer":{
"email_address":"a#yandex.com",
"payer_id":"WEJUPTK4U53E9",
"address":{
"address_line_1":"1 Main St",
"admin_area_2":"San Jose",
"admin_area_1":"CA",
"postal_code":"95131",
"country_code":"US"
},
"name":{
"given_name":"a",
"surname":"som"
},
"phone":{
"phone_number":{
"national_number":"408-214-8270"
}
}
},
"purchase_units":[{
"reference_id":"default",
"amount":{
"value":"1.01",
"currency_code":"USD"
},
"payee":{
"email_address":"gr-facilitator#yandex.com",
"merchant_id":"MSOIGVMKKWAMA"
},
"shipping":{
"name":{
"full_name":"Mr T"
},
"address":{
"address_line_1":"1234 Main St.",
"address_line_2":"Unit 1",
"admin_area_2":"Chicago",
"admin_area_1":"IL",
"postal_code":"60652","country_code":"US"
}
},
"payments":{
"captures":[{
"status":"COMPLETED",
"id":"0TA12948FV40723B",
"final_capture":true,
"create_time":"2019-02-20T05:06:52Z",
"update_time":"2019-02-20T05:06:52Z",
"amount":{
"value":"1.01","currency_code":"USD"
},
"seller_protection":{
"status":"ELIGIBLE",
"dispute_categories":[
"ITEM_NOT_RECEIVED",
"UNAUTHORIZED_TRANSACTION"
]}
}
]}
}]
}
Since purchase_units and captures are arrays:
details.purchase_units[0].payments.captures[0].id
captures key have objects in side an array. so you can't simply fetch like
details.purchase_units.payments[0].captures.id
you have to give the position of the captures or loop the array only you can do parsing
details.purchase_units.payments[0].captures[0].id
If you add your json as object using the chrome console you will be able to do what I did in in the image below. purchase_unit is an array so you need to access it using the index.
In case if you want to capture all the IDs in an array, you can use wild card:
details.purchase_units[*].payments.captures[*].id
This will parse complete payload for specified path and collect all the IDs in an array.

How to access object field in server array response?

I made a parse.com get request, the returned data is stored in:
$scope.tastes = data.results
{
"createdAt": "2016-03-16T07:39:15.745Z",
"objectId": "Cmg8GdOv2Z",
"updatedAt": "2016-03-16T07:39:15.745Z",
"user": {
"__type": "Pointer",
"className": "_User",
"objectId": "vYOsndWlto"
},
"userTastes": [
{
"actualite": {
"checked": true
},
"economie": {
"checked": true
},
"entrepreneuriat": {
"checked": false
}
}
]
}
Well, I want to get userTastes array.
I've tried
.success(function (data, status) {
$scope.tastes = data.results.userTastes;
console.log($scope.tastes);
})
However nothing is returned. I think that I'm missing something.
My question : How do I get userTastes in $scope.tastes ?
I writing a separate answer because I believe this needs further explanation and not just the fix to your problem.
You only provided an object response in your question, but apparently you are getting an array response from your server, while you can directly access object fields, on array objects you need to access the position first, Ex:
$scope.objectResponse = {"foo":"bar"};
console.log($scope.objectResponse.foo); // Will print "bar"
in contrast array responses:
$scope.arrayResponse = [{"foo":"bar"}];
console.log($scope.arrayResponse[0].foo); // Will print "bar"
Just make sure you are getting the response you want from your server.
results[0].userTastes work worked perfectly thanks !
If someone have a tutorial link or good course about array and objects in JS because I'm a little bit confused about that.
Have a good day !

How to add text to beginning and ending of JSON to make it JSONP

I'm working on a project, I can manually add a beginning name and parenthesis: bio(
and an ending ) to the end of my JSON data to make it callable as JSONP.
I am going to do this to about 200 files which is why I'm trying to find a solution to do this in code.
I've tried using regex, converting to a string, trying to convert back, etc, and nothing seems to work.
My abbreviated JSON data is below:
{
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
What I want is:
bio({ <--------
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}) <-------
I've gotten closest with Stringify and regex:
var myString = JSON.stringify(workbook);
var change = myString.replace(/^/,"bioInfo(").replace(/$/,")”);
When I try to change it back to an object so I can use it though, it fails saying:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I've tried eval as well trying to get it to change back to an object but it just doesn't seem to work.
Hopefully my dilemma is clear and someone knows a good way to do this in Javascript or Jquery.
Thanks in advance.
You don't need anything as complicated as you are making it. Just concatenate your strings.
var jsonp = "bio(" + json + ");"
I've gotten closest with Stringify
JSON is already a string. You only need to stringify something if you have a JavaScript data structure and want to convert it to JSON.

How to get the name of the array in json data using JavaScript

I have a JSON object which comes back like this from a JavaScript API call:
{
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
How can I access the name of the array (i.e myArray) in JavaScript. I need to use the name of the array to determine the flow later on.
Use getOwnPropertyNames to get a list of the properties of the object in array form.
Example:
var myObj = {
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
},
names = Object.getOwnPropertyNames(myObj);
alert(names[0]); // alerts "myArray"
Note: If the object can have more than one property, like myArray, myInt, and myOtherArray, then you will need to loop over the results of getOwnPropertyNames. You would also need to do type-testing, as in if(names[0] instanceof Array) {...} to check the property type. Based on your example in your question, I have not fleshed all of that out here.
Object.keys(data)[0]
# => "myArray"
A terminology note: This solution assumes you have a JavaScript object. You might have a JSON string, in which case this is the solution:
Object.keys(JSON.parse(data))[0]
# => "myArray"
However, "JSON object", in JavaScript, is just one - the one I used just now, that has JSON.parse and JSON.stringify methods. What you have is not a JSON object except perhaps in a trivial interpretation of the second case, where all values in JavaScript are objects, including strings.
The other answers are good if you have no control over the return format.
However, if you can, I'd recommend changing the return format to put the important values you care about as actual values instead of keys to make it clearer. For example, something like this:
result =
{
"name: "myArray",
"value": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
Then, it's a lot clearer to reliably access the property you care about: result.name

How to manipulate JSON object to remove root key within Javascript?

I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});

Categories