javascript - 为什么我尝试设置带有值的 JSON 字段时会出现此错误?未捕获的类型错误 : Cannot set property 'today_avg_price' of undefined

标签 javascript json

我不太喜欢 JavaScript,我正在疯狂地尝试执行这个脚本,从一个 JSON 文档开始创建另一个 JSON 文档:

(我将我的示例放入html文件并在Chrome上调试它,您可以执行相同的操作来测试它):

<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    function checkForNull(value) {
        if (value instanceof Object && "@nil" in value) {
            return null;
        }

        return value;
    }

    console.log("START")

    var payload = JSON.parse(`
        {
            "Markets": {
                "Market": {
                    "market_name": "Tambacounda Market N1",
                    "market_description": "Tambacounda Market N1",
                    "localization_id": 2,
                    "long": 13.776796,
                    "lat": -13.672198,
                    "country": "Senegal",
                    "regione": {
                        "@nil": "true"
                    },
                    "province": {
                        "@nil": "true"
                    },
                    "city": {
                        "@nil": "true"
                    },
                    "district": {
                        "@nil": "true"
                    },
                    "town": {
                        "@nil": "true"
                    },
                    "village": {
                        "@nil": "true"
                    },
                    "commodity": {
                        "el": [{
                                "commodity_details_id": 4,
                                "commodity_name_en": "Red onion",
                                "commodity_name": "Red onion",
                                "image_link": "Red_onion.jpg",
                                "today_avg_price": 20.1500,
                                "yesterday_avg_price": 33.3300,
                                "currency": "XOF",
                                "measure_unit": "kilogram",
                                "price_series_id": 1
                            }, {
                                "commodity_details_id": 6,
                                "commodity_name_en": "Green Beans",
                                "commodity_name": "Green Beans",
                                "image_link": "Green_Beans.jpg",
                                "today_avg_price": {
                                    "@nil": "true"
                                },
                                "yesterday_avg_price": 778.0000,
                                "currency": "RWF",
                                "measure_unit": "kilogram",
                                "price_series_id": 17
                            }
                        ]
                    }
                }
            }
        }
    `);

    // create new response          
    var response = payload.Markets.Market;
    console.log("RESPONSE: " + JSON.stringify(response));

    // convert null values
    response.regione = checkForNull(response.regione);
    response.province = checkForNull(response.province);
    response.city = checkForNull(response.city);
    response.district = checkForNull(response.district);
    response.town = checkForNull(response.town);
    response.village = checkForNull(response.village);

    // convert array of commodities into required HATEOS format
    var commodity = new Array();

    for (i = 0; i < response.commodity.el.length; ++i) {
        var el = response.commodity.el[i];  
        var newEl = new Object();
        newEl.commodity_name = el.commodity_name;
        newEl.commodity.today_avg_price = el.today_avg_price;
        newEl.commodity.yesterday_avg_price = el.yesterday_avg_price;
        newEl.rel = "commodity_details";
        newEl.href = "http://5.249.148.180:8280/commodity_details/" + el.commodity_details_id;
        newEl.type = "GET";

        commodity.push(newEl);
    }

    response.commodity = commodity;


    console.log("END");
  </script>

  <p>...After the script.</p>

</body>

</html>

如您所见,原始文档已放入有效负载对象中。

问题出现在for循环中第一次迭代的这一行:

newEl.commodity.today_avg_price = el.today_avg_price;

并给出此错误消息:

parse_json_market.html:97 Uncaught TypeError: Cannot set property 'today_avg_price' of undefined
at parse_json_market.html:97

如您所见,此 JSON 字段包含 20.1500

"today_avg_price": 20.1500,
为什么?问题是什么?我缺少什么?我该如何解决这个问题?

最佳答案

您只需在 newEl.commodity.today_avg_price 之前添加此代码

newEl.commodity = new Object();

原因是因为newElobject,但newEl.commodityundefined。 因此,在调用 newEl.commodity.today_avg_price 之前,您必须将 newEl.commodity 设置为对象。

FIDDLE

关于javascript - 为什么我尝试设置带有值的 JSON 字段时会出现此错误?未捕获的类型错误 : Cannot set property 'today_avg_price' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46664885/

相关文章:

javascript - "innerHTML += ..."与 "appendChild(txtNode)"

json - 如何使用 postman 发布对象和列表

java - 根据 swagger 文件验证 json 有效载荷 - json-schema-validator

javascript - 显示本地 JSON 文件中的数据

javascript - JSON,获取数据

javascript - 自定义 CKEditor

javascript - jQuery:访问与 anchor 标记相邻的元素的值

javascript - 使用 jQuery 将光标更改为自定义图像

javascript匿名函数语法

javascript - 通过环境变量获取 MQTT 节点密码