【问题标题】:Filter the JSON object and write the results in the local .json file过滤 JSON 对象并将结果写入本地 .json 文件
【发布时间】:2018-11-30 02:45:24
【问题描述】:

我获取了一个 API 并获得了一个 JSON 对象,我需要对其进行过滤并存储在一个新的本地 json 文件中。

返回结果,但我想不出一种方法来过滤 json 文件(数据)并将其正确写入新的 newfile.json 文件。

 .then(
      json => { 
        const data = JSON.stringify(json)
        const filtered = data.map( //some filter function )
        fs.writeFile('src/data/newfile.json', filtered, 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }

        console.log("The file was saved!");
    }); 

这是我从一系列调查中获得的 json 数据示例。

{
        "surveyId": 515315,
        "reviewId": "34152",
        "transactionInfo": {
          "transactionRef": "1806001511991",

          "transactionCity": "Plymouth",
          "transactionState": "MN",
          "transactionType": null,
          "customerFirstName": "Kristine",
        },
        "serviceProviderInfo": {
          "serviceProviderName": "Lobster",
          "serviceProviderEmail": "lobster@bayeq.com",
          "serviceProviderId": 43346,
          "serviceProviderOfficeName": "Oakdale - 30152501",
          "serviceProviderRegionName": "Minnesota - Chacich",
          "serviceProviderOfficeId": 721581,
          "serviceProviderRegionId": 151563
        },
        "review": {
          "source": "encompass",
          "rating": "5.0",
          "summary": null,
          "description": "He was fantastic ",
          "agreedToShare": true,
          "verifiedCustomer": true,
          "retakeSurvey": false,
          "surveyResponses": [
            {
              "question": "How would you rate the service and support you received?",
              "type": "Numeric",
              "answer": "5"
            },
            {
              "question": "Please rate the level of advice and communication you received from [name].",
              "type": "Numeric",
              "answer": "5"
            },
            {
              "question": "How likely are you to refer friends and family to [name]?",
              "type": "Numeric",
              "answer": "10"
            },
            {
              "question": "How would you rate your overall experience?",
              "type": "Experience",
              "answer": "Great"
            }
          ],
          "reportedAbusive": false
        },
        "reviewStatus": "completed"
      }

如何过滤并创建一个新的 JSON 文件,其结构类似于

{
    "email": "foo@bar.com",
    "rating": 4.56,
    "testimonials": [{
        "description": "Fugiat ut sed occaecat.",
        "firstname": "Bob",
        "city": "Bananatown",
        "state": "TH"
    }]
}

【问题讨论】:

  • 在您粘贴的输入中找不到预期输出中的数据。您能否详细说明一下转换是如何发生的?也许发布更有意义的数据子集和相应的预期输出?
  • 什么是用于 dat 获取的 js,如 jqury 或 angular 或其他

标签: javascript reactjs


【解决方案1】:

这里我用了jquery

var datat = {
            "surveyId": 515315,
            "reviewId": "34152",
            "transactionInfo": {
                "transactionRef": "1806001511991",

                "transactionCity": "Plymouth",
                "transactionState": "MN",
                "transactionType": null,
                "customerFirstName": "Kristine",
            },
            "serviceProviderInfo": {
                "serviceProviderName": "Lobster",
                "serviceProviderEmail": "lobster@bayeq.com",
                "serviceProviderId": 43346,
                "serviceProviderOfficeName": "Oakdale - 30152501",
                "serviceProviderRegionName": "Minnesota - Chacich",
                "serviceProviderOfficeId": 721581,
                "serviceProviderRegionId": 151563
            },
            "review": {
                "source": "encompass",
                "rating": "5.0",
                "summary": null,
                "description": "He was fantastic ",
                "agreedToShare": true,
                "verifiedCustomer": true,
                "retakeSurvey": false,
                "surveyResponses": [
                    {
                        "question": "How would you rate the service and support you received?",
                        "type": "Numeric",
                        "answer": "5"
                    },
                    {
                        "question": "Please rate the level of advice and communication you received from [name].",
                        "type": "Numeric",
                        "answer": "5"
                    },
                    {
                        "question": "How likely are you to refer friends and family to [name]?",
                        "type": "Numeric",
                        "answer": "10"
                    },
                    {
                        "question": "How would you rate your overall experience?",
                        "type": "Experience",
                        "answer": "Great"
                    }
                ],
                "reportedAbusive": false
            },
            "reviewStatus": "completed"
        };

        datat.review.surveyResponses = datat.review.surveyResponses.filter(function (a) {
            return a.answer === "10";
        });

        var sd = datat.review.surveyResponses[0].question;
        alert(sd);

【讨论】:

    【解决方案2】:

    我在这里做一些猜测。正如已经指出的那样,样本输入和样本输出之间存在如此多的差异,以至于读者对可用的映射推断没有信心。我所依赖的相关性与样本输出的结构不一致,但这些是唯一合理的选项。


    另外,我认为您可能不想对传入的数据进行字符串化。你希望它是一个对象,所以你可以直接寻址数据;如果数据以字符串形式传入,则需要将其解析为带有JSON.parse的对象


    这里有一些可行的方法。我已经链接了.then 调用,以便更轻松地插入新步骤并在必要时对其重新排序。我省略了任何错误处理,但是如果您正在解析从 Internet 接收的字符串,您将需要一些可以处理输入字符串不是有效 JSON 时将引发的错误的东西。

    .then(string => JSON.parse(string)) // only needed if your earlier promise returns a string
    .then(json => ({
        email: json.serviceProviderInfo.serviceProviderEmail,
        rating: json.review.rating,
        testimonials: [{
            description: json.review.description,
            firstname: json.transactionInfo.customerFirstName,
            city: json.transactionInfo.transactionCity,
            state: json.transactionInfo.transactionState
        }]
    }))
    .then(summary => {
        return fs.writeFile('src/data/newfile.json', JSON.stringify(summary), 'utf8', function (err) {
            if (err) {
                return console.log(err);
            }
            console.log("The file was saved!");
            return true
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多