0

I have a state-abbreviation json file from here. In my .js file, I have var=state that I want to look up the abbreviation for. So I need help in finding how to do that. For example lookup state (=Maine) in the json to get the "ME" value. Please help! Newbie in javascript so please please be as basic as possible in your answer. Thanks

Update So my json is fine. Here is a sample from it...

[{"Alabama": "AL","Alaska": "AK","American Samoa": "AS",.....})

In my .js file, I am 'trying' to get the json file and use it for lookup like so. Obviously this isn't working. I know there are many mistakes so please be nice when helping out. Remember I am a newbie. ;-)

$.getJSON("/files/json/states_hash.json", function(json){
var data = eval("(" + json.responseText +")");
var val=_.findValue(json, stateNameVar);
console.log(json);
});
5
  • 3
    Why don't you invert (using a simple script) your json? That means you create a new json where the key is "Maine" and the value is "ME"... for example: var new_json = Object.keys(your_json).reduce(function(obj, key){ obj[your_json[key] ] = key; return obj; }, {}); Commented Aug 30, 2017 at 16:18
  • What do you mean by 'local'? You can't read files from the filesystem with JavaScript without user input. Commented Aug 30, 2017 at 16:20
  • Do you need full explanation starting from "how to get json from server", or just a way to lookup for the value ? Commented Aug 30, 2017 at 16:20
  • @Jared He probably means "server-side". Commented Aug 30, 2017 at 16:20
  • The first thing to know when handling JSON in JavaScript is that it means JavaScript Object Notation, and that you should simply be handling objects rather than their text/json representation. You can transform from and to JSON with a process called (de)serialization (or sometimes (un)marshalling) Commented Aug 30, 2017 at 16:25

3 Answers 3

2

Building upon Matteo's comment, an option is to run a simple one-time script to reverse the keys/values. This makes the lookups you're trying to do fairly trivial:

// here's what you have now:
const states = { 'VA': 'Virginia', 'CO': 'Colorado' };
console.log(states);

// this flips the keys/values:
const flippedStates = {};
Object.entries(states).forEach(([k,v]) => { flippedStates[v] = k })
console.log(flippedStates);

// lookup by full name:
console.log(flippedStates['Virginia']);
console.log(flippedStates['Colorado']);

Weave in JSON.parse/stringify where needed.

Sign up to request clarification or add additional context in comments.

Comments

0

Since the abbreviation in this case is the key, you'll want to use an appropriate method to find a key by its value. That will depend on what you have available to you. Several methods of doing as such can be found here: JavaScript object get key by value

Now, you'll also have to load the JSON into the page. Again, this depends on your environment (node.js, in browser, etc.). With node.js it'd be as simple as const states = require("./states.json");, but in browser there are several different methods with different trade offs that are better described here: Loading local JSON file

4 Comments

A link to an answer is not an answer. Explain here why the links are relevant and how they can help the OP.
Updated to give a little more context to the links, although this question is still a little ambiguous so it's hard to give a direct answer.
If your answer is a link to another answer, you should just click the "flag" button under the question and flag it as a duplicate question.
In this case, it was a combination of two answers which required some level of synthesis.
0

If I understand correctly your question you are trying to invert the key / value relation of a Json. You can simply invert it programmatically with something like that may be the more efficient things to do:

var data = { /*your json */ }
var newData = Object.keys(data).reduce(function(obj,key){
  obj[ data[key] ] = key;
  return obj;
},{});

OR without using external libraries (it is not too much efficient):

function getKeyByValue(data, state) {
  return Object.keys(data).find(key => data[key] === state);
}

OR you can use external libraries. It is up to you.

From your code:

I've put on Gist a JSON like the one that you are using You can test this code below... (Sorry but due to CORS policy I have to insert this very long address to the Gist).

var json_file = "https://gist.githubusercontent.com/MatteoRagni/71280e5be2281347d915f90a60b7167b/raw/f3cf77fb2755461be96d03023226220583d6939d/state2_hash.json";
var state = "Maine";

$.getJSON(json_file, function(json) {
  console.log(json[state]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

9 Comments

I shouldn't need to invert anything since my json is the way i need it to be with the state-name as the key and the state-abbreviation as the value. Right? So in my console I see that the variable json is picking up my file after the first line. $.getJSON("/rinlocator/json/states_hash.json", function(json){... So is there a way to do something like var stateAbbreviation = json.lookup(stateName)
You are meaning something like json["Alabama"] to get "AL"? or json.Alabama even works...
Below is my method. Chrome debugger shows me state1="Maine" but val is undefined! Why isn't val getting the "ME" value that it should? $.getJSON("/files/json/states_hash.json", function(json){ var val = json[state1]; console.log(val); });
try this: $.getJSON("/files/json/states_hash.json", function(json){ var val = json[state1]; console.log(val); conole.log(state1); });. does it prints "undefined \n Maine"?
Yes it does. I need it to print undefined \n ME instead
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.