Access JSON Array with Javascript? - javascript

I get an JSON array via an Ajax request. This one looks like this:
{
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
}
But I have no idea, how to access the JSON array. I already tried all of this:
success: function(data) {
console.log(data[0].data.title);
console.log(data[0].title);
console.log(data.data[0].title);
console.log(data.title);
}
Can you guys give me a hint?
Kind regards

You have tried everything except:
data.data.title
It's an Object and you need to use Object.key() or something to iterate. Technically, it's like this:
// Inside your function, this is what gets passed.
data = {
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
};
for (var key in data.data) {
console.log(`${key}: ${data.data[key]}`);
}

data is not an array, nor JSON, it's an object literal. Your last try comes close, but you need to access
data.data.title
or you could destructure data in the success param
success: function({data}) {
// now you could access data.title directly
console.log(data.title);
}

Related

error when using "push()" to add string to JSON array

I want to add strings to my JSON file which looks like this:
{
"items": []
}
which is required like this: var items = require("../../config/item.json");
Then I am writing it to the array like this: items["item"].push(str);,
which triggers an error: Cannot read property 'push' of undefined
How can I add the string "str" to the array?
After pushing it, i write it to the file like this:
let data = JSON.stringify(items);
fs.writeFileSync("../../config/item.json", data, (err) => {
if (err) {
throw err;
} else {
console.log("item written successfully.");
}
});
Thanks in advance.
You need to use the push() method on the array, your property selector ['item'] doesn't exist it's ['items']. The json file itself is not an array, it's an object.
To push in to the array:
var items = require("../../config/item.json");
items.items.push(str);
Or you can do items['items'].push(str) where ['items'] is a property selector.

How to dynamically extract data from vue object for a POST request to backend?

I have a vue object with all these getters and setters, here is a screenshot from the console.log:
The structure of the actual DATA (the not-vue stuff) looks like this:
{
Internal_key: "TESTKEY_1",
extensiontable_itc: {
description_itc: "EXTENSION_ITC_1_1",
description_itc2: "EXTENSION_ITC_1_2",
},
extensiontable_sysops: {
description_sysops: "EXTENSION_SYSOPS_1"
}
}
The data might look different in other usecases.
There might be more or less key-value pairs on the outer object, and the keys might be named differently as well. Same goes for the nested objects and their contents.
Is there some convenient way to extract this data into a plain JS Object?
If not, how can I best loop the vue object to extract the data "manually"?
The AJAX request shall be performed by an axios request, if this is important as well.
EDIT:
Here is the relevant data in vue:
data() {
return {
editingRecord: {
original: null,
copy: null
}
}
}
During my programflow, both editingRecord.orginal and editingRecord.copy receive data from an inputform. copy sets its data to original if the user clicks the save/send button. Then, I want to take the data from editingRecord.original with both its keys and values and send them to the server via AJAX request.
Its best not to mix jQuery with Vue so here's how you would do it using Axios https://github.com/axios/axios
methods: {
submit() {
const body = this.editingRecord.original
// make changes to body
axios.post( "backend_url", body )
.then(function(resp){
console.log(resp)
});
}
}
Okay, I found the solution.
let vueObject = Object.entries(this.editingRecord.original)
for(const[key, value] of vueObject){
if(typeof value == 'object' && value !== null){
for(const [nestedKey, nestedValue] of Object.entries(value)){
result[nestedKey] = nestedValue
}
}else{
result[key] = value
}
}
console.log("resultObject is", result)
This way you can iterate over all properties including the properties of nested objects and reassign both key and value to a fresh, one-dimensional array.

Pulling Out Value from Within Two-Levels Deep Object

I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}
From:
console.log(userInfo);
I get this back in the console:
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
What I want to do is specifically pull out the "_id" value here.
I tried:
console.log(userInfo.data._id);
But then my IDE is showing me an error:
'Property '_id' does not exist on type 'string'.
How do I dig out "_id" in this case?
You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.
I also see that you are getting
'Property '_id' does not exist on type 'string'.
This could mean that you never parsed the information. To find out if this is the case this should be right:
Running->
console.log(userInfo);
Returns->
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
Just after this code:
Running->
console.log(typeof userInfo);
Returns->
"string"
With your edits, I can see that this is the case.
Try:
userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
The _id property is under the data key:
const response = {
"token":"sometoken.value",
"data": {
"_id":"8cd0362c0",
"phone":"555-4343"
}
};
console.log(response.data._id)
You can also use destructuring:
const { _id } = response.data;
console.log(_id)
or:
const { data: { _id }} = response;
console.log(_id);
So, as #jonsharpe pointed out, the key was to JSON.parse the string first. So this gets me the value I need for "_id":
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = JSON.parse(sessionStorage.getItem('currentUser'));
console.log(userInfo.data._id);
}
}
Actually your string is returned as JSON string. So you have to parse it into object using JSON.parse() if you are using js or with $.parseJSON() if you are using Jquery. So your updated code now looks like this.
var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);
And Fiddle is here.
Thank You

How to read from JSON in protractor test?

I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"object_type_s:USER",
"indent":"true",
"wt":"json"
}
},
"response":{
"numFound":13,
"start":0,
"docs":[
{
"id":"sanja",
"groups_id_ss":[
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
},
{
"id":"sanjaseconduser",
"groups_id_ss":[
"ACM_SUPERVISOR_DEV",
"CHAIRMAN",
"ACM_ADMINISTRATOR_DEV",
"CPC INITIATOR",
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
}
]
}
}
As stated you could read response.docs from json. Let's say
var docs = response.docs;
As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
var groupIdSS = doc.groups_id_ss;
}
});
This way you can read groups_id_ss for desired id.
Hope it helps.
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData = require('../../response.json');
describe('some function description', function(){
var groupID = responseData.response.docs[0].groupid_ss[0];
var groupID = responseData.response.docs[0].groupid_ss[0]
});
Since that is json array, we have to give the index of the array in that.
Hope this would work for you.

json variable is undefined

I have a json file in a folder called json/img_desc.json
Here is the json file
{ "theimages":[
{
"number":1,
"title":"Joy Toy teddy bear",
"description":"In etc etc"
} etc etc
Then I used this code to try and get the first value.
$.getJSON('json/img_desc.json', function(theimages) {
console.log(img_desc.theimages.number[0]);
});
The error
It says this
[15:06:46.951] ReferenceError: img_desc is not defined #
file:///[removed for privacy]/js/puzzle.js:246
it should be
$.getJSON('json/img_desc.json', function (theimages) {
console.log(theimages.theimages[0].number);
//if you want to loop
$.each(theimages.theimages, function (idx, obj) {
console.log(obj.number)
})
});
Documentation says http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- it will pass a plain object as the second parameter. So, you can do something like this
$.getJSON('json/img_desc.json', function(theimages) {
$.each(theimages.theimages, function( index, val ) {
console.log(val, val.number);
});
});
$.getJSON('json/img_desc.json', function(img_desc) {
console.log(img_desc.theimages.number[0]);
});
Should fix your problem. As if you have any other problem, ask it in a separate question.

Categories

Resources