Skip to content

# basic_json::update

    // (1)
    void update(const_reference j);

    // (2)
    void update(const_iterator first, const_iterator last);

1. Inserts all values from JSON object `j` and overwrites existing keys.
2. Inserts all values from from range `[first, last)` and overwrites existing keys.

The function is motivated by Python's dict.update function.

## Parameters

`j` (in)
  JSON object to read values from
`first` (in)
  begin of the range of elements to insert
`last` (in)
  end of the range of elements to insert

## Exceptions

1. The function can throw thw following exceptions:
   - Throws `type_error.312` if called on JSON values other than objects; example: `"cannot use update() with string"`
2. The function can throw thw following exceptions:
   - Throws `type_error.312` if called on JSON values other than objects; example: `"cannot use update() with string"`
   - Throws `invalid_iterator.202` if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"`
   - Throws `invalid_iterator.210` if `first` and `last` do not belong to the same JSON value; example: `"iterators do not fit"`

## Complexity

1. O(N*log(size() + N)), where N is the number of elements to insert.
2. O(N*log(size() + N)), where N is the number of elements to insert.

## Example

Example

The example shows how `update()` is used.

    #include <iostream>
    #include <iomanip>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // create two JSON objects
        json o1 = R"( {"color": "red", "price": 17.99} )"_json;
        json o2 = R"( {"color": "blue", "speed": 100} )"_json;

        // add all keys from o2 to o1 (updating "color")
        o1.update(o2);

        // output updated object o1
        std::cout << std::setw(2) << o1 << '\n';
    }

Output:

    {
      "color": "blue",
      "price": 17.99,
      "speed": 100
    }

Example

The example shows how `update()` is used.

    #include <iostream>
    #include <iomanip>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // create two JSON objects
        json o1 = R"( {"color": "red", "price": 17.99} )"_json;
        json o2 = R"( {"color": "blue", "speed": 100} )"_json;

        // add all keys from o2 to o1 (updating "color")
        o1.update(o2.begin(), o2.end());

        // output updated object o1
        std::cout << std::setw(2) << o1 << '\n';
    }

Output:

    {
      "color": "blue",
      "price": 17.99,
      "speed": 100
    }

## Version history

- Added in version 3.0.0.