DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. How to Run Find/Replace on a JSON Object Graph

How to Run Find/Replace on a JSON Object Graph

Justin Bozonier user avatar by
Justin Bozonier
·
Oct. 16, 12 · Interview
Like (0)
Save
Tweet
Share
8.67K Views

Join the DZone community and get the full member experience.

Join For Free

Today I had cause to implement a method for finding and replacing a value that appears at the end of a certain JSON path in an object graph. I couldn't find a pre-existing tool to do the dirty work, so I wrote it myself, and then wrote this article. :)

Here's a concrete example. Imagine you have the following JSON:

{
  "CompanyData" =>
  [
    {
      "Name"=>"Company A",
      "Employees"=>
      [
        {
          "Status"=>"Awesome",
          "Name" => "Employee 42",
          "ShirtColor" => "Purple",
          "FavoriteFood" => "Pizza"
        },
        {
          "Name" => "Employee 1",
          "ShirtColor" => "Green",
          "FavoriteFood" => "Rocks",
          "Status"=>"BAD",
        },
      ]
    },
    {
      "Name"=>"Company B",
      "Employees"=>
      [
        {
          "Status"=>"Awesome",
          "Name" => "Another Employee",
          "ShirtColor" => "Maroon",
          "FavoriteFood" => "Your Mom",
          "Manages" =>
          [
            {
              "Name" => "Mofo",
              "ShirtColor" => "Teal",
              "FavoriteFood" => "Blood",
              "Status"=>"Awesome",
             },
          ],
          "Wife" =>
          {
            "ShirtColor"=>"Purple"
          }
        },
        {
          "Name" => "THE IMP",
          "ShirtColor" => "Mauve",
          "Status"=>"BAD",
        },
      ]
    },
  ]
}

Now imagine that you want to make the shirt color of every employee with a status of awesome orange. Why? No clue. Work with me here. How would you accomplish that?

After looking for someone else having already done this, I set out to do it myself and was surprised at how simple this was in Ruby. The technique I thought of was to search through every  node in the object graph and call a special replace function on each one. If the given node matched the criteria, then it or its children would be updated accordingly.

The following code amounts to a depth first search of the object graph:

def search node, &replacement_action
  if node.class() == Hash
    node.each_value do |item|
      yield item
      search item, &replacement_action
    end
  else
    if node.class() == Array
      node.each do |item|
        yield item
        search item, &replacement_action
      end
    end
  end
end

search companies do |node|
  if node.class() == Hash
    node["ShirtColor"] = "Orange" if node["Status"] == "Awesome"
  end
end

Really all of the "magic" is in the search method which really just knows how to enumerate either a Hash or an Array, call the replace method and then recursively search its children. If the child object fails some aspect of the replace criteria, nothing happens, we just move on searching through all of its children's Hash or Array children and so on until no other options exist.

What's most surprising to me is the simplicity and elegance of the solution. I probably spent more time looking for an alternate than it took me to write that code.

Now before you think that this will only work in the simplest of cases, here is the actual replacement code I needed for my real world scenario:

def replace_on_node node, value_to_find, replacement_value
  objectType = node.class()
  if objectType == Hash
    if node.has_key? "KeyOverride"
      key_override_object = node["KeyOverride"]
      if key_override_object.class() == Hash
        if key_override_object.has_key? "_Data"
          data_object = key_override_object["_Data"]
          if data_object.class() == Array
            data_object.each do |item|
              if item.class() == Hash
                if item["<Value>k__BackingField"].class() == Hash
                  if item["<Id>k__BackingField"] == 0 && item["<Value>k__BackingField"]["<Value>k__BackingField"] == value_to_find
                    puts "Replaced!"
                    item["<Value>k__BackingField"]["<Value>k__BackingField"] = replacement_value
                  end
                end
              end
            end
          end
        end
      end
    end
  end
end

 

JSON Object (computer science) Graph (Unix)

Published at DZone with permission of Justin Bozonier, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed Stateful Edge Platforms
  • Cloud-Based Transportation Management System
  • Unlocking the Power of Polymorphism in JavaScript: A Deep Dive
  • Apache Kafka vs. Memphis.dev

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: