Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
please give me your guidance.
I'm using node with mysql database (without using orm).
i use snake_case naming convention for mysql.
my question is:
in node,
should i use snake_case or use camelCase ?
for e.g. at models/movie.js:
snake_case:
return db.execute(SELECT title, daily_rental_rate FROM movies);
the result sent to the client:
{
title: 'abc',
daily_rental_rate: 20
}
camel_case:
return db.execute(SELECT title, daily_rental_rate as dailyRentalRate FROM movies);
the result sent to the client:
{
title: 'abc',
dailyRentalRate: 20
}
thank you so much /\
There is no fixed convention for JSON casing, however most APIs tend to use camelCase for properties, include Google, see their style guide here.
You can also map object properties within JavaScript, you don't have to do this manually in your queries. This allows you to be relatively flexible with your casing, even changing to kebab-case or snake_case if you wish to later on. This example uses the lodash library to convert object case.
const _ = require("lodash");
function objectToCamelCase(obj) {
return _.mapKeys(obj, (v, k) => _.camelCase(k))
}
let rows = db.execute("SELECT title, daily_rental_rate FROM movies");
console.log("Result (snake_case): ", rows);
rows = rows.map(objectToCamelCase);
console.log("Result (camelCase):", rows);
The results might look like so:
Result (snake_case):
[
{
"title": "The Shawshank Redemption",
"daily_rental_rate": "€2.99"
},
{
"title": "Ferris Bueller's Day Off",
"daily_rental_rate": "€2.99"
}
]
Result (camelCase):
[
{
"title": "The Shawshank Redemption",
"dailyRentalRate": "€2.99"
},
{
"title": "Ferris Bueller's Day Off",
"dailyRentalRate": "€2.99"
}
]
Related
I'm trying to get the titles of reddit posts from a subreddit in React, using Axios for fetching.
I can fetch the JSON from here, and would like to get the data of each object (post/comment) separately (so I can show titles, post text and the like in the render() part of the component).
Here's the first lines of that JSON, pretty-printed:
{
"kind": "Listing",
"data": {
"modhash": "",
"dist": 27,
"children": [
{
"kind": "t3",
"data": {
"approved_at_utc": null,
"subreddit": "reactjs",
"selftext": "Previous two threads - [June 2019](https:\/\/www.reddit.com\/r\/reactjs\/comments\/bvxng8\/beginners_thread_easy_questions_june_2019\/) and [May 2019](https:\/\/www.reddit.com\/r\/reactjs\/comments\/bjgval\/beginners_thread_easy_questions_may_2019\/). \n\nGot questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We\u2019re a friendly bunch. \n\nNo question is too simple. \ud83e\udd14\n\n---------------------------------------------\n\n\ud83c\udd98 **Want Help with your Code?** \ud83c\udd98\n\n* **Improve your chances** by putting a minimal example to either [JSFiddle](https:\/\/jsfiddle.net\/Luktwrdm\/) or [Code Sandbox](https:\/\/codesandbox.io\/s\/new). Describe what you want it to do, and things you've tried. Don't just post big blocks of code!\n\n* **Pay it forward!** Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than [being wrong on the Internet](https:\/\/xkcd.com\/386\/). \n\n**Have a question regarding code \/ repository organization?**\n\nIt's most likely answered within this [tweet](https:\/\/twitter.com\/dan_abramov\/status\/1027245759232651270?lang=en).\n\n---------------------------------------------------\n\n**New to React?**\n\n**Check out the sub's sidebar!**\n\n\ud83c\udd93 Here are great, **free** resources! \ud83c\udd93\n\n* [Create React App](https:\/\/facebook.github.io\/create-react-app\/)\n* [Read the **official** Getting Started page](https:\/\/reactjs.org\/docs\/getting-started.html) on the docs.\n* [\/u\/acemarke](https:\/\/www.reddit.com\/u\/acemarke)'s [suggested resources for learning React](http:\/\/blog.isquaredsoftware.com\/2017\/12\/blogged-answers-learn-react\/)\n* [Kent Dodd's Egghead.io course](http:\/\/kcd.im\/beginner-react)\n* [Tyler McGinnis' 2018 Guide](https:\/\/medium.freecodecamp.org\/a-comprehensive-guide-to-react-js-in-2018-ba8bb6975597)\n* [Codecademy's React courses](https:\/\/www.codecademy.com\/catalog\/language\/javascript)\n* [Scrimba's React Course](https:\/\/scrimba.com\/g\/glearnreact)\n* [Robin Wieruch's Road to React](https:\/\/roadtoreact.com)\n\n-----\n\nAny ideas\/suggestions to improve this thread - feel free to comment here!\n\n----\n_Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!_",
"author_fullname": "t2_2aun3ozb",
"saved": false,
"mod_reason_title": null,
"gilded": 0,
"clicked": false,
"title": "Beginner's Thread \/ Easy Questions (July 2019)",
"link_flair_richtext": [
],
Here's my component (without the render part, just what happens after that fetch is complete - i.e. the componentDidMount() function):
componentDidMount() {
axios.get(`https://www.reddit.com/r/reactjs.json`)
.then (
res => {
const posts = res.data.data.children.map(obj => obj.data);
this.setState({posts});
}
);
}
This works perfectly.
My question is - why?
My logic would go - get res -> look for data -> look for children -> look for data, then map() that data object into the data object for posts.
Instead, what seems to work is - get res -> look for data -> look for data -> look for children, then do the mapping.
That's how axios parses the response json object. They store it under their own personal data key. It just so happens that within the json object provided by Reddit, they also have a field called data that holds the children array you want.
It might be more helpful to name your variables like so:
componentDidMount() {
axios.get(`https://www.reddit.com/r/reactjs.json`)
.then((res) => {
const redditJson = res.data
const posts = redditJson.data.children.map(obj => obj.data)
this.setState({
posts: posts
})
})
}
I am creating a API using nodejs. The API takes request and responds in JSON
For example:
I have a table QUESTION in my database so a GET request to endpoint http://localhost/table/question will output the table in JSON format.
However there is a problem when performing JOINS
Considering tables QUESTION and CHOICE. A question has many choices (answers) their join will be
Table:
I am trying to convert to something like this
{
"0":{
"QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
"OPTION":{
"A":"3 Bytes",
"B":"32 Bits",
"C":"64 Bits",
"D":"12 Bytes"
}
},
"1":{
"QUESTION":"Which one is not a SFR",
"OPTION":{
"A":"PC",
"B":"R1",
"C":"SBUF"
}
},
"2":{
"QUESTION":"What is Size of DPTR in 8051",
"OPTION":{
"A":"16 Bits",
"B":"8 Bytes",
"C":"8 Bits"
}
},
"3":{
"QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
"OPTION":{
"A":"Yes",
"B":"No"
}
}
}
The obvious solution is to parse it query using JOIN and convert it to JSON.
Is there any more efficient way to do it?
In MySQL you can achieve this with group_concat
tablenames, fieldnames, etc are pure fantasy :-)
select
q.text as question,
group_concat(answer.label, ';;;') as labels,
group_concat(answer.text, ';;;') as answers
from
question as q
join answer as a on a.quesion = q.id
group by
q.text
And then in your application (nodejs)
let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
let texts = row.answers.split(';;;');
return {
question: row.question,
options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
}
});
This question already has answers here:
Update MongoDB field using value of another field
(12 answers)
Closed 6 years ago.
I am trying to do a query that seems to be basic on the surface. However, I cannot seem to do it efficiently and elegantly. Namely, I have the following document:
{
id:
runtime: {
start: Date
end: Date
total: number
}
events: [runtime1, runtime2, ...]
}
Upon a certain API call, I would like to set the runtime.end to the current date and then push what is contained in the runtime object into the events array.
Here is the code I have been trying to use for it:
router.get('/stop/:id', function(req,res){
var collection = db.get('Activity');
collection.update({
_id: req.params.id
},
{
$set: {
"runtime.started": false,
"runtime.endDate": new Date()
},
$push: {events: {
startDate: new Date,
endDate: new Date
}
}
},
function(err, activity){
if (err) throw err;
res.json(activity);
});
});
Any idea how this can be done? The code above seem to do nothing, except to edit the runtime object.
P.S. I found several questions and answers circa 2010 - 2012 that stated that this could not be done. Have things changed since then?
Check your MongoDB version. You may need to upgrade to the newest one. Also, try with the $push by itself (without the set, just as in the MongoDB docs example).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want the key and value of the following multidimensional array with key :followersperdate
{"version":"1.2","username":"LGUS","url":"http://t.co/ospRRVboge","avatar":"http://pbs.twimg.com/profile_images/378800000016800237/3787f02f0e0e10a0a19d9b508abd6ce2_normal.png","followers_current":38775,"date_updated":"2013-11-15","follow_days":"774","started_followers":544,"growth_since":38231,"average_growth":"49","tomorrow":"38824","next_month":"40245","followers_yesterday":37232,"rank":"14934","followersperdate":{"date2013-11-15":38775,"date2013-11-05":37232,"date2013-11-04":37126,"date2013-10-26":36203,"date2013-10-10":34384,"date2013-10-02":33353,"date2013-09-18":30870},"last_update":1384679796}
i cleared it for you, the object you want, has 7 sub objects, that can parse base on your language,
check this web page to learn more, choose your language, at the bottom of the site:
http://www.json.org/
if you are on a javaScript, check this http://www.w3schools.com/json/json_intro.asp
{
"version": "1.2",
"username": "LGUS",
"url": "http://t.co/ospRRVboge",
"avatar": "http://pbs.twimg.com/profile_images/378800000016800237/3787f02f0e0e10a0a19d9b508abd6ce2_normal.png",
"followers_current": 38775,
"date_updated": "2013-11-15",
"follow_days": "774",
"started_followers": 544,
"growth_since": 38231,
"average_growth": "49",
"tomorrow": "38824",
"next_month": "40245",
"followers_yesterday": 37232,
"rank": "14934",
"followersperdate": {
"date2013-11-15": 38775,
"date2013-11-05": 37232,
"date2013-11-04": 37126,
"date2013-10-26": 36203,
"date2013-10-10": 34384,
"date2013-10-02": 33353,
"date2013-09-18": 30870
},
"last_update": 1384679796
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am working on designing the JSON document of my data. Below is a single value (v) which contains site-id, price-score and confidence-score for now.
{
"v" : {
"site-id" : 0,
"price-score" : 0.5,
"confidence-score" : 0.2
}
}
Now, I want to add categories list into the above JSON document. As I am going to have multiple categories for a single value (v) so I came up with below JSON document-
{
"v" : {
"site-id" : 0,
"price-score" : 0.5,
"confidence-score" : 0.2,
"categories": [
{
"category-id": "123",
"price-score": "0.5",
"confidence-score": "0.2"
},
{
"category-id": "321",
"price-score": "0.2",
"confidence-score": "0.4"
}
]
}
}
Can anyone take a look and let me know if it looks good in the way I have added list of categories in the above JSON document? Or is there any better way of doing the same? As I don't want to start having problems when I am working on serializing and deserializing the above JSON document.
I recommend:
{
"v" : {
"site-id" : 0,
"price-score" : 0.5,
"confidence-score" : 0.2,
"categories": {
"123" : {
"price-score": "0.5",
"confidence-score": "0.2"
},
"321" : {
"price-score": "0.2",
"confidence-score": "0.4"
}
}
}
}
This way, you can easily use:
json.v.categories[id]
to get information about a specific category, instead of having to write:
var the_category;
for (var i = 0; i < json.v.categories.length; i++) {
if (json.v.categories[i]['category-id'] == id) {
the_category = json.v.categories[i];
break;
}
}
Another suggestion: use _ rather than - in the keys (or camelCase if you prefer), as hyphen prevents you from using . notation to access elements (notice that I had to write ['category-id'] above instead of .category-id.