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);
});
  • 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; }, {});` – Matteo Ragni Aug 30 '17 at 16:18
  • What do you mean by 'local'? You can't read files from the filesystem with JavaScript without user input. – Jared Smith Aug 30 '17 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 ? – Vyacheslav Aug 30 '17 at 16:20
  • @Jared He probably means "server-side". – juanferrer Aug 30 '17 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) – Aaron Aug 30 '17 at 16:25

3 Answers3

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.

shabs
  • 718
  • 3
  • 10
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

Steven Goodman
  • 576
  • 3
  • 15
  • A link to an answer is not an answer. Explain here why the links are relevant and how they can help the OP. – juanferrer Aug 30 '17 at 16:24
  • 1
    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. – Steven Goodman Aug 30 '17 at 16:30
  • 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. – GrumpyCrouton Aug 30 '17 at 18:15
  • In this case, it was a combination of two answers which required some level of synthesis. – Steven Goodman Aug 30 '17 at 18:17
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>
Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34
  • 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) – user3294636 Aug 30 '17 at 17:15
  • You are meaning something like `json["Alabama"]` to get `"AL"`? or `json.Alabama` even works... – Matteo Ragni Aug 30 '17 at 17:33
  • 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); }); – user3294636 Aug 30 '17 at 17:43
  • 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"? – Matteo Ragni Aug 30 '17 at 18:07
  • Yes it does. I need it to print undefined \n ME instead – user3294636 Aug 31 '17 at 19:14
  • Check the answer again, please. – Matteo Ragni Aug 31 '17 at 19:48
  • I am looking at it right now. Its the same. For some reason the lookup function isn't working. So it means there is something with the lookup function? I did this console.log(json) and that prints an object with all the states-abbreviations. [Object] 0 : Object Alabama : "AL" Alaska : "AK" American Samoa : "AS" Arizona : "AZ" – user3294636 Aug 31 '17 at 19:55
  • Ah! Your json is inside an Array?? try `console.log(json[0][state]);` – Matteo Ragni Aug 31 '17 at 19:57
  • Yes!!!! Thank you so much. That worked. I don't know how to mark this as the correct answer. – user3294636 Aug 31 '17 at 20:08