将json取消嵌套到分为键和值列的多行

时间:2019-10-01 11:51:56

标签: google-bigquery

我想取消嵌套 public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> { private TextView viewName, viewPrice; private CheckBox viewAvailability; private Context context; private List<Item> listItems; @NonNull @Override public ItemAdapter.ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); return new ItemAdapter.ItemHolder(view); } @Override public void onBindViewHolder(@NonNull ItemAdapter.ItemHolder holder, int position) { Item item = listItems.get(position); holder.setDetails(item); } @Override public int getItemCount() { return listItems.size(); } public class ItemHolder extends RecyclerView.ViewHolder { public ItemHolder(final View itemView) { super(itemView); viewName = itemView.findViewById(R.id.viewName); viewPrice = itemView.findViewById(R.id.viewPrice); viewAvailability = itemView.findViewById(R.id.viewAvailability); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } public void setDetails(Item item) { viewName.setText(item.getName()); viewPrice.setText(item.getPrice()); int as = item.getAvailabilityStatus(); if (as == 1) { viewAvailability.setChecked(true); } else { } } } public ItemAdapter(Context context, List<Item> objects) { this.context = context; this.listItems = objects; } 列的内容: json_blob 看起来像这样:

SELECT '{"a": [1, 2, 3], "b": [4, 5, 6]}' AS json_blob

请注意,不同的行可以具有不同的键,并且有很多键。我不想用手全部写下。

2 个答案:

答案 0 :(得分:0)

JSON的架构必须保持不变,然后您可以执行以下操作:

with t as (SELECT '{"a": [1, 2, 3], "b": [4, 5, 6]}' AS json_blob)

select key, val
from t cross join unnest([
  struct('a' as key, json_extract(json_blob, '$.a') as val), 
  struct('b' as key, json_extract(json_blob, '$.b') as val)
])

答案 1 :(得分:0)

下面的示例可能是一个很好的起点-但实际上取决于json的模式

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '{"a": [1, 2, 3], "b": [4, 5, 6]}' AS json_blob UNION ALL
  SELECT '{"a": [11, 12, 13], "c": [14, 15, 16]}' UNION ALL
  SELECT '{"d": 21, "b": [24, 25, 26]}' 
)
SELECT 
  SPLIT(kv, ': ')[OFFSET(0)] AS key,
  SPLIT(kv, ': ')[SAFE_OFFSET(1)] AS value
FROM `project.dataset.table`,
  UNNEST(REGEXP_EXTRACT_ALL(json_blob, r'("\w+":[^"]*)(?:,|})')) kv   

有结果

Row key value    
1   "a" [1, 2, 3]    
2   "b" [4, 5, 6]    
3   "a" [11, 12, 13]     
4   "c" [14, 15, 16]     
5   "d" 21   
6   "b" [24, 25, 26]