-2

I need to parse this JSON feed and set the values is prop variables to JS variables

{'propMap':{'pageName':'dsfdsf:dsfdsf:home','prop1':'dsfds:dsf','prop46':'OD','prop5':'/content','prop24':'A Taste Of Home','prop6':'1c4074ca-89bf-4d9f-8bd2-a5dc5f3ecf74','prop3':'Home','prop70':'OD','prop4':'show','prop71':'desktop','prop10':['xxx'],'prop11':['xxx'],'channel':'OD'}}

After i parse these values i have to set these values

like s.prop2= value in map and i don't want to do this statically for every variable would be nice if i can use the loop to do it. Can anybody please help.

Sam Thadhani
  • 585
  • 1
  • 10
  • 21
  • do you mean you want to set each key/value pair into a new variable with the name being the key and the value being the value of the map? – ZekeDroid Aug 19 '14 at 05:51
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – toesslab Aug 19 '14 at 05:52
  • I don't think he's trying to parse a json blob, I think he's trying to dynamically set variable names – ZekeDroid Aug 19 '14 at 05:54
  • @ZekeDroid, yes you are absolutely correct. I want to first parse the json and then set the variable where the key name would be the name of my variables. The variables names are important as they will be used for analytics – Sam Thadhani Aug 19 '14 at 06:08

1 Answers1

0

If what you're trying to do is to dynamically set variable names given the keys in your map, then you'd want to use a loop to find each key/value pair (you can use underscore.js for this) and then use the global window attribute to set the paired values:

_.each(parseJsonFile, function(value, key) {
    window[key] = value;
});

You can also use eval() but it's a dangerous tool sometimes as you could be inadvertently setting variables you did not expect to set.

EDIT:

Demo,

var parseJsonFile = {'var1':'something', 'var35':'other'}; 
_.each(parseJsonFile, function(value, key) {
    window[key] = value;
});

You will now have var1 = 'something' and var35 = 'other'.

ZekeDroid
  • 7,089
  • 5
  • 33
  • 59
  • this is literally the demo example. parseJsonFile should be your already parsed JSON file. So if you set var parsedJsonFile = to that map you posted already, then use that code and it will set the variables you want. of course, note that you have nested maps, in which case you'll need either multiple loops or to reduce your problem to single level maps. – ZekeDroid Aug 19 '14 at 06:14
  • I can still resolve my data to format of string, string just to make life simple if needed be. – Sam Thadhani Aug 19 '14 at 06:16
  • no, the parsed json file is much cleaner for this type of task. – ZekeDroid Aug 19 '14 at 06:17