How to re-order JSON in BaseX for conversion to CSV?

岁酱吖の 提交于 2020-03-06 09:43:46

问题


I have JSON data which is just slightly backwards in that the "name" key should be first. The desired output as CSV:

people
alice,z10,y9,x7,atrib6
sue,home5,cell4
joe,phone3,phone2,phone1

It only matters that the "name" for the CSV is first, the rest of the order is arbitrary and meaningless.

Through the BaseX GUI I can export this data as:

,z10,y9,x7,atrib6,alice
home5,cell4,sue
phone3,phone2,phone1,joe
people

by selecting CSV, although that leading comma looks odd. However, this is very much the structure I want from the original data:

joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10

where no record was deliminated. The assumption and pattern is that the "name" has no digits, all attributes have digits. This seems to hold for the original data, this is just dummy data for testing.

populating a dummy database from generated JSON:

thufir@dur:~/flwor/json$ 
thufir@dur:~/flwor/json$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> create database blgdfmbljm
Database 'blgdfmbljm' created in 226.99 ms.
> 
> exit
Have a nice day.
thufir@dur:~/flwor/json$ 
thufir@dur:~/flwor/json$ basex createDB.xq 
thufir@dur:~/flwor/json$ 
thufir@dur:~/flwor/json$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> open blgdfmbljm
Database 'blgdfmbljm' was opened in 216.47 ms.
> 
> xquery .
<json type="array">
  <_ type="object">
    <_0030/>
    <_0031>z10</_0031>
    <_0032>y9</_0032>
    <_0033>x7</_0033>
    <_0034>atrib6</_0034>
    <name>alice</name>
  </_>
  <_ type="object">
    <_0030>home5</_0030>
    <_0031>cell4</_0031>
    <name>sue</name>
  </_>
  <_ type="object">
    <_0030>phone3</_0030>
    <_0031>phone2</_0031>
    <_0032>phone1</_0032>
    <name>joe</name>
  </_>
  <_ type="object">
    <name>people</name>
  </_>
</json>
Query executed in 212.93 ms.
> 
> exit
Enjoy life.
thufir@dur:~/flwor/json$ 

the XQuery to load the data:

let $database := "blgdfmbljm"
for $name in file:list('.', false(), '*.json')
let $file := file:read-text($name)
let $json := json:parse($file)
return db:add($database, $json, $name) 

来源:https://stackoverflow.com/questions/60251056/how-to-re-order-json-in-basex-for-conversion-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!