Skip to content

How to create a json variable? #990

Description

@miketing629

Bug Report

  • What is the issue you have?

This is more of a question than an issue. The sample code illustrates what I'm trying to do, and the included output shows it's not working the way I hope/expect. I've tried other variations than what is in the sample - can't get anything to work.

  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?

Build and run this code:

void jsonTest()
{
    try
    {
        nlohmann::json v1 = nlohmann::json::parse("{ \"a\":{\"b\":{\"c\":{\"value\":900}}} }");
        auto value1 = v1["a"]["b"]["c"].value("value", 0);

        std::cout << "value1: " << value1 << std::endl;
    }
    catch (...)
    {
        printf("value1: exception");
        std::cout << "value1: exception" << std::endl;
    }

    try
    {
        nlohmann::json v2 =
        {
            "a",
            {
                "b",
                {
                    "c",
                    {
                        "value", 900
                    }
                }
            } 
        };
        auto value2 = v2["a"]["b"]["c"].value("value", 0);

        std::cout << "value1: " << value2 << std::endl;
    }
    catch (...)
    {
        std::cout << "value2: exception" << std::endl;
    }

    try
    {
        nlohmann::json v3 =
        {
            {
                "a",
                {
                    "b",
                    {
                        "c",
                        {
                            "value", 900
                        }
                    }
                }
            }
        };
        auto value3 = v3["a"]["b"]["c"].value("value", 0);

        std::cout << "value3: " << value3 << std::endl;
    }
    catch (...)
    {
        std::cout << "value3: exception" << std::endl;
    }
}
  • What is the expected behavior?

All cases print the value 900.

  • And what is the actual behavior instead?

This is the output of the code:

value1: 900
value2 : exception
value3 : exception

Visual Studio 2017, Windows 10

  • Did you use a released version of the library or the version from the develop branch?

Released version 3.1.1.

Feature Request

  • Describe the feature in as much detail as possible.

  • Include sample usage where appropriate.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions