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.
Related
There are two things I want to do:
I want to create a new array of objects from an existing object,
And increment the object so each object can have a count id of 1,2,3 etc
My issue is that when I write to the file it writes only 1 random object to the file and the rest don't show. There are so errors and all the objects have the same increment value. Please explain what I am doing wrong. Thanks.
Code:
data.json:
{
"users":[
{
"name":"mike",
"category":[
{
"title":"cook",
}
],
"store":{
"location":"uptown",
"city":"ulis"
},
"account":{
"type":"regular",
"payment":[
"active":false
]
}
}
]
}
index.js:
const appData = ('./data.json')
const fs = require('fs');
let newObject = {}
appData.forEach(function(items){
let x = items
let numincrement = 1++
newObject.name = x.name
newObject.count = numincrement
newObject.categories = x.categories
newObject.store = x.store
newObject.account = x.account
fs.writeFile('./temp.json', JSON.stringify(newObject, null, 2),'utf8' , function(err, data) {
// console.log(data)
if(err) {
console.log(err)
return
} else{
console.log('created')
}
})
})
There are a whole bunch of problems here:
You're just rewriting the same object over and over to the file. fs.writeFile() rewrites the entire file. It does not append to the file. In addition, you cannot append to the JSON format either. So, this code will only every write one object to the file.
To append new JSON data to what's in the existing file, you would have to read in the existing JSON, parse it to convert it to a Javascript array, then add new items onto the array, then convert back to JSON and write out the file again. For more efficient appending, you would need a different data format (perhaps comma delimited lines).
Your loop has all sorts of problems. You're assigning to the same newObject over and over again.
Your numincrement is inside the loop so it will have the same value on every invocation of the loop. You can also just use the index parameter passed to the forEach() callback instead of using your own variable.
If what you're trying to iterate over is the users array in your data, then you may need to be iterating over appData.users, not just appData.
If you really just want to append data to a text file, the JSON is not the easiest format to use. It might be easier to just use comma delimited lines. Then, you can just append new lines to the file. Can't really do that with JSON.
If you're willing to just overwrite the file with the current data, you can do this:
const appData = ('./data.json').users;
const fs = require('fs');
// create an array of custom objects
let newData = appData.map((item, index) => {
return {
name: item.name,
count: index + 1,
categories: item.categoies,
store: item.store,
account: item.account
};
});
// write out that data to a file as JSON (overwriting existing file)
fs.writeFile('./temp.json', JSON.stringify(newData, null, 2),'utf8' , function(err, data) {
if (err) {
console.log(err);
} else {
console.log("data written");
}
});
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);
}
This question already has an answer here:
how to build json array dynamically in javascript
(1 answer)
Closed 6 years ago.
I receive a json object with some number of quick reply elements from wit.ai, like this:
"msg": "So glad to have you back. What do you want me to do?
"action_id": "6fd7f2bd-db67-46d2-8742-ec160d9261c1",
"confidence": 0.08098269709064443,
"quickreplies": [
"News?",
"Subscribe?",
"Contribute?",
"Organize?"
],
"type": "msg"
I then need to convert them to a slightly different format as they are passed to FaceBook Messenger as described in the code below. Wit only exposes 'msg' and 'quickreplies.' Can you suggest a good way to do this? It goes after "console.log(element)" as far as I understand.
if (quickreplies){
// got simple array of quickreplies
// need to format quickreplies for FB:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"Red",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
// },
// {
// "content_type":"text",
// "title":"Green",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
// }]
console.log('we got quickreplies, here they are:');
var quick_replies = []; // ??
quickreplies.forEach(function(element) {
console.log(element)
});
}
else (console.log('no quickreplies'));
In the above example, the end result should be this:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"News",
// "payload":"News"
// },
// {
// "content_type":"text",
// "title":"Subscribe?",
// "payload":"Subscribe?"
// }
// "content_type":"text",
// "title":"Contribute?",
// "payload":"Contribute?"
// },
// {
// "content_type":"text",
// "title":"Organize?",
// "payload":"Organize?"
// }
// ]
Most straightforward way, I think, would be to convert the JSON into an object using JSON.parse().
Then manipulate the object, removing and adding elements as needed.
Once done, using JSON.stringify to convert the object back into a JSON string.
Maybe this can help you out.
function makeReply(text) {
return { content_type: 'text', title: text, payload: text };
}
var replies = { quick_replies: [] };
quickreplies.forEach(function(element) {
replies.quick_replies.push(makeReply(element); // not sure what needs to be supplied for "title" and "payload"
});
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.
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);