0

I am trying to create a function that takes an input. Which in this case is a tracking code. Look that tracking code up in a JSON file then return the tracking code as output. The json file is as follows:

[ { "tracking_number": "IN175417577", "status": "IN_TRANSIT", "address": "237 Pentonville Road, N1 9NG" }, { "tracking_number": "IN175417578", "status": "NOT_DISPATCHED", "address": "Holly House, Dale Road, Coalbrookdale, TF8 7DT" }, { "tracking_number": "IN175417579", "status": "DELIVERED", "address": "Number 10 Downing Street, London, SW1A 2AA" } ] 

I have started using this function:

def compare_content(tracking_number) File.open("pages/tracking_number.json", "r") do |file| file.print() end 

Not sure how I would compare the input to the json file. Any help would be much appreciated.

1 Answer 1

1

You can use the built-in JSON module.

require 'json' def compare_content(tracking_number) # Loads ENTIRE file into string. Will not be effective on very large files json_string = File.read("pages/tracking_number.json") # Uses the JSON module to create an array from the JSON string array_from_json = JSON.parse(json_string) # Iterates through the array of hashes array_from_json.each do |tracking_hash| if tracking_number == tracking_hash["tracking_number"] # If this code runs, tracking_hash has the data for the number you are looking up end end end 

This will parse the JSON supplied into an array of hashes which you can then compare to the number you are looking up.

If you are the one generating the JSON file and this method will be called a lot, consider mapping the tracking numbers directly to their data for this method to potentially run much faster. For example,

{ "IN175417577": { "status": "IN_TRANSIT", "address": "237 Pentonville Road, N1 9NG" }, "IN175417578": { "status": "NOT_DISPATCHED", "address": "Holly House, Dale Road, Coalbrookdale, TF8 7DT" }, "IN175417579": { "status": "DELIVERED", "address": "Number 10 Downing Street, London, SW1A 2AA" } } 

That would parse into a hash, where you could much more easily grab the data:

require 'json' def compare_content(tracking_number) json_string = File.read("pages/tracking_number.json") hash_from_json = JSON.parse(json_string) if hash_from_json.key?(tracking_number) tracking_hash = hash_from_json[tracking_number] else # Tracking number does not exist end end 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.