将具有不同类型对象(字符串,数组)的JSON转换为Map

时间:2015-10-26 15:50:30

标签: arrays json hive brickhouse

我正在尝试使用brickhouse lib` brickhouse.udf.json.FromJsonUDF``将JSON对象转换为Hive中的地图对象。

问题是,我的json对象包含不同类型的值:string和另一个数组的一个数组。

我的json看起来像这样:

'{"key1":"value1","key2":"value2","key3":"value3","key4":[["0","1","nnn"],["1","3","mmm"],["1","3","ggg"],["1","5","kkk"],["4","5","ppp"]]}'

我可以使用以下内容正确读取数组元素数组(key4):

select from_json('{"key1":"value1","key2":"value2","key3":"value3","key4":[["0","1","nnn"],["1","3","mmm"],["1","3","ggg"],["1","5","kkk"],["4","5","ppp"]]}', 'map<string,array<array<string>>>') from my_table limit 1;

Which gives me:

{"key1":[],"key3":[],"key2":[],"key4":[["0","1","nnn"],["1","3","mmm"],["1","3","ggg"],["1","5","kkk"],["4","5","ppp"]]}

正如您所见,key4以外的所有元素都是空的。

或者我可以使用以下内容阅读key4以外的其他元素

select from_json('{"key1":"value1","key2":"value2","key3":"value3","key4":[["0","1","nnn"],["1","3","mmm"],["1","3","ggg"],["1","5","kkk"],["4","5","ppp"]]}', 'map<string,string>') from my_table limit 1;

Which gives me:

{"key1":"value1","key3":"value3","key2":"value2","key4":null}

但是如何将所有元素正确转换为生成的地图对象上的键值对?

EDITED

我的实际数据是两个组件的数组,它们是json对象:

[{"key1":"value1", "key2":"value2"}{"key3":"value3","key4":"value4","key5":"value5","key6":[["0","1","nnn"],["1","3","mmm"],["1","3","ggg"],["1","5","kkk"],["4","5","ppp"]]}]

是否可以创建一个struct对象,其中包含两个json对象作为两个地图对象,以便我可以访问第一个或第二个struct元素,然后使用键选择相应的地图对象的值?

例如:假设我的所谓endresult被调用struct_result我将从第一个组件访问value1,如:

struct_result.t1["key1"]

这会给我&#34; value1&#34;。

用这个lib可以实现这个吗?

1 个答案:

答案 0 :(得分:1)

这可以使用named_structs来完成。您需要创建一个named_struct,并单独指定每个键的类型。

例如

class CustomTableViewCell: UITableViewCell {        
var viewController : MyViewController?
var cellNo = 0
//and so on
}

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var sliderValues: [Float] = []

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {    
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as! CustomTableViewCell 
cell.Label1.text = "Long Tongue, size \(indexPath.row) cm"
cell.Label2.text = "Big Banana, size \(indexPath.row) inches"
self.sliderValues.append (0.0) // just to be sure that each slider can put it's value to Array

cell.cellNo = indexPath.row // so the Custom Cell knows it's No

//---------------------//
cell.viewController = self
//---------------------//

return cell
    }
}

//----------------------
//and back to Custom Cell
@IBAction func sliderValueChanged(sender: AnyObject) {
    self.viewController?.sliderValues[self.cellNo] = self.customSlider.value
}

// and the same way with UISwitch

这使用&#39; named_struct&#39;创建模板对象。 UDF,或者您可以使用等效的字符串类型定义。