最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How do I update the data saved in a JSON file using JavaScript? - Stack Overflow

programmeradmin6浏览0评论

How do I update the data saved in a JSON file using JavaScript?

for example: If i have a JSON file called 'person.json', looking like:

{
  "Person": [
    {
      "Firstname": "John",
      "Lastname": "Doe"
    }
  ]
}

and I would like to append as new data set the name 'John Smith'. How could I do this using JavaScript?

EDIT: Now I tried to use 'fs.readFile()' to read my JSON file. The application I develop is a hybrid app using cordova. If i use 'fs.readFile()' i get the error 'Uncaught ReferenceError: fs is not defined'. I tried to fix this problem by adding the line 'var fs = Npm.require('fs');'. But this causes also an error: 'Uncaught ReferenceError: Npm is not defined'

Is this error caused because npm is not available on a smartphone? And how can i fix this problem?

How do I update the data saved in a JSON file using JavaScript?

for example: If i have a JSON file called 'person.json', looking like:

{
  "Person": [
    {
      "Firstname": "John",
      "Lastname": "Doe"
    }
  ]
}

and I would like to append as new data set the name 'John Smith'. How could I do this using JavaScript?

EDIT: Now I tried to use 'fs.readFile()' to read my JSON file. The application I develop is a hybrid app using cordova. If i use 'fs.readFile()' i get the error 'Uncaught ReferenceError: fs is not defined'. I tried to fix this problem by adding the line 'var fs = Npm.require('fs');'. But this causes also an error: 'Uncaught ReferenceError: Npm is not defined'

Is this error caused because npm is not available on a smartphone? And how can i fix this problem?

Share Improve this question edited Jul 2, 2021 at 12:31 phuzi 13.1k4 gold badges29 silver badges59 bronze badges asked May 30, 2017 at 14:17 DominikDominik 872 gold badges2 silver badges15 bronze badges 2
  • 4 Possible duplicate of How to write data to a JSON file using Javascript – cнŝdk Commented May 30, 2017 at 14:19
  • Are you trying to do it server side, am I right? If it's a browser app, you'll need a back-end that handles the JSON file, and then call it from your javascript running in the browser. The good news is that you can do the back-end using javascript to, see node.js – Rômulo M. Farias Commented May 30, 2017 at 14:25
Add a ment  | 

1 Answer 1

Reset to default 3

You can simply use JSON.parse(data) to parse the JSON string into an object. Then when you're done, use JSON.stringify(object) to convert it into a JSON string.

You can write and read files with fs link.

发布评论

评论列表(0)

  1. 暂无评论