Is it a possible to import a JSON file in node.js update some properties in the JSON then write the new data back into place?
是否可以在node.js中导入JSON文件更新JSON中的一些属性然后将新数据写回原位?
Would it be better to use fs
to read the file then write the file again?
使用fs读取文件然后再次写入文件会更好吗?
I am trying to whip up a stupid simple prototype DB using JSON.
我试图使用JSON掀起一个愚蠢的简单原型数据库。
export const Users = [
{
username: 'Mike'
}
]
export const Websites = [
{
owner: 'Mike',
website: 'michael-aubry',
build: {
header: {
component: 'header',
navigation: 'standard'
},
main: {
works: true,
card: 1
}
}
}
]
export const Works = [
{
owner: 'Mike',
items: [
{title: 'Dribbble Thanks', image_src: './dribbble_thanks.png'},
{title: 'My WIP', image_src: 'bloomthat.png'},
{title: 'Michael Angelo', image_src: 'https://d13yacurqjgara.cloudfront.net/users/371472/screenshots/2847709/studio-minted-case-studies-promo.jpg'},
{title: 'Beautiful Art', image_src: 'https://d13yacurqjgara.cloudfront.net/users/4094/screenshots/2846992/drib106.jpg'}
]
}
]
1 个解决方案
#1
1
Let's think about this in a slightly different way.
让我们以略微不同的方式思考这个问题。
We can't use import
to write back to a JSON file, and if the JSON file shouldn't permanently change, we don't necessarily want to write back to it.
我们不能使用import来回写JSON文件,如果JSON文件不能永久更改,我们不一定要回写它。
What if you had a module that read the JSON file, and then other files would import this module to use and manipulate that data?
如果您有一个读取JSON文件的模块,然后其他文件将导入此模块以使用和操作该数据,该怎么办?
// data.json
{
"users": ...,
"websites": ...,
"works": ...
}
// data.js
import data from './data.json'
export default data
And now you can import from data.js
and modify those values.
现在您可以从data.js导入并修改这些值。
#1
1
Let's think about this in a slightly different way.
让我们以略微不同的方式思考这个问题。
We can't use import
to write back to a JSON file, and if the JSON file shouldn't permanently change, we don't necessarily want to write back to it.
我们不能使用import来回写JSON文件,如果JSON文件不能永久更改,我们不一定要回写它。
What if you had a module that read the JSON file, and then other files would import this module to use and manipulate that data?
如果您有一个读取JSON文件的模块,然后其他文件将导入此模块以使用和操作该数据,该怎么办?
// data.json
{
"users": ...,
"websites": ...,
"works": ...
}
// data.js
import data from './data.json'
export default data
And now you can import from data.js
and modify those values.
现在您可以从data.js导入并修改这些值。