L
L
Lord_North2021-05-02 16:11:23
JavaScript
Lord_North, 2021-05-02 16:11:23

How to access json record?

Hello. I don't understand why I can't change the value in json.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.novaposhta.ua/v2.0/json/",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
  },
  "processData": false,
  "data": "{\r\n\"apiKey\": \"edfa683c0e325e5afd444a8fb1121d90\",\r\n \"modelName\": \"Address\",\r\n \"calledMethod\": \"searchSettlements\",\r\n \"methodProperties\": {\r\n \"CityName\":\"киев\",\r\n \"Limit\": 10\r\n }\r\n}"
};
JSON.parse(settings.data).methodProperties.CityName="дол";
alert(JSON.parse(settings.data).methodProperties.CityName);

The alert continues to show "Kyiv", didn't I change the value to "dol"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-05-02
@Lord_North

The JSON.parse function creates a new object and therefore changing it does not affect the state of the original object.

// Parse settings.data into separate variable
let settings_data = JSON.parse(settings.data);

// Update settings_data object by new value
settings_data.methodProperties.CityName="дол";

// Update settings.data by new stringified value
settings.data = JSON.stringify(settings_data);

// Test
alert(JSON.parse(settings.data).methodProperties.CityName);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question