The .json file is like
"person":{"_info":{"name":"john","age":17}}
In my node, if i run console.log(person.body); it prints out fine, but if I try console.log(person._info.body); or console.log(person._info); it returns undefined.
So is there a way that I can print out the ._info?
Thanks
May be your json isn't valid, this code is working :
var obj = {
"person": {
"_info": {
"name":"john",
"age":17
}
}
};
console.log(obj.person._info);
Related
I'm using Cypress with Mocha Junit to do e2e testing for React in Chrome. The default behavior is for it to have one single output for results each time it runs my tests, and it overwrites the file every time. I'd like to have it keep these files in like a log.
The config is in a JSON file that looks like this:
}
"projectId": "XXXXXX",
"reporter": "junit",
"reporterOptions": {
"mochaFile": "./cypress/results/my-test-output.xml",
"toConsole": true
}
}
I'd like to do something like
var date = new Date();
"mochaFile": "./cypress/results/my-test-output${date}.xml",
Obviously this isn't valid JSON. How can I rig this up to make it generate something unique each time?
From the docs,
Results XML filename can contain [hash]
Also, if you check the junit reporter source, you can see how is doing it:
...
this.writeXmlToDisk(xml, this._options.mochaFile);
...
MochaJUnitReporter.prototype.writeXmlToDisk = function(xml, filePath){
if (filePath) {
if (filePath.indexOf('[hash]') !== -1) {
filePath = filePath.replace('[hash]', md5(xml));
} ...
So, you could just have:
"mochaFile": "./cypress/results/my-test-output[hash].xml"
Nothing to do here. As you can see all you need to do is wrap your JSON in backticks. Except that I'd suggest you use Date.now() instead of new Date().
let date = Date.now();
let json = `{
"projectId": "XXXXXX",
"reporter": "junit",
"reporterOptions": {
"mochaFile": "./cypress/results/my-test-output-${date}.xml",
"toConsole": true
}
}`
let parsedJson = JSON.parse(json)
console.log(parsedJson.reporterOptions.mochaFile)
Compared to a hash this even has the advantage of historization.
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
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.
I have a user specified JSON object that I'm attempting to process in the browser.
The problem is that it needs to match an existing object.
They can't accidentally:
forget to include some fields.
typo fields or deliberately add new fields.
Is there a way to handle this?
so basically if I have an object with foo and bar members, I want their defaults if the user's json is just {} ... and if they accidentally send something like {bart: "asdf";} (typo on 'bar') then I want it to generate an exception.
var default_object = { ... };
var allowed_keys = [ "key1", "key2", ... ];
var new_object = default_object.clone();
for (var key in json_object) {
if (json_object.hasOwnProperty(key)) {
if (allowed_keys.indexOf(key) == -1) {
// Report error here
} else {
new_object[key] = json_object[key];
}
}
}
See here for how to write the clone method I used above. If you use jQuery, you could simplify some of this code by using $.extend().
I have this json file, and I'm turning into a json array, everything works fine, but the real json file contains more data.
How to simplify this code could either change the javascript or json file.
{
"Subject1":{
"Biology":{
"Category":{
"Cell":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2":"what's....?"
},
"question3":{
"que3": "what's....?"
}
},
"Bactery":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2": "what's....?"
},
"question3":{
"que3": "what's....?"
}
}
}
}
}
}
this is my code witch convert the file json into array json of javascript:
var exa = [];
function show() {
$.getJSON('questions.json', function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
exa.push({
//I want to simplify this part, because the real json file have more questions
que1: item.Biology.Category.Cell.question1.que1,
que2: item.Biology.Category.Cell.question2.que2,
que3: item.Biology.Category.Cell.question3.que3,
que11: item.Biology.Category.Bactery.question1.que1,
que12: item.Biology.Category.Bactery.question2.que2,
que13: item.Biology.Category.Bactery.question3.que3
});
}
}
//return Books;
console.log(exa)
})
}
Instead of que1, que2, etc., just have the questions in an array
"Cell": [
"what's this?",
"what's that?"
]
You can use json-path and write JsonPath.read(json, "$..question"); to get all questions. You need to change all que[*] in your file to question too.