簡體   English   中英

使用不同的鍵將嵌套的 JSON 轉換為 JavaScript 中的節點和鏈接結構

[英]Converting Nested JSON to nodes and links structure in JavaScript with different keys

我想將我的原始 JSON 數組數據轉換為

      "data": {
        "name": "Sint Maarten",
        "introduction": {
          "background": "Although sighted by Christopher COLUMBUS in 1493 and claimed for Spain, it was the Dutch who occupied the island in 1631 and began exploiting its salt deposits. The Spanish retook the island in 1633, but the Dutch continued to assert their claims. The Spanish finally relinquished the island of Saint Martin to the French and Dutch, who divided it between themselves in 1648. The establishment of cotton, tobacco, and sugar plantations dramatically expanded African slavery on the island in the 18th and 19th centuries; the practice was not abolished in the Dutch half until 1863. The island's economy declined until 1939 when it became a free port; the tourism industry was dramatically expanded beginning in the 1950s. In 1954, Sint Maarten and several other Dutch Caribbean possessions became part of the Kingdom of the Netherlands as the Netherlands Antilles. In a 2000 referendum, the citizens of Sint Maarten voted to become a self-governing country within the Kingdom of the Netherlands, effective October 2010. On 6 September 2017, Hurricane Irma hit Saint Martin/Sint Maarten, causing extensive damage to roads, communications, electrical power, and housing. The UN estimated the storm destroyed or damaged 90% of the buildings, and Princess Juliana International Airport was heavily damaged and closed to commercial air traffic for five weeks."
        },
        "geography": {
          "location": "Caribbean, located in the Leeward Islands (northern) group; Dutch part of the island of Saint Martin in the Caribbean Sea; Sint Maarten lies east of the US Virgin Islands",
          "geographic_coordinates": {
            "latitude": {
              "degrees": 18,
              "minutes": 4,
              "hemisphere": "N"
            },
            "longitude": {
              "degrees": 63,
              "minutes": 4,
              "hemisphere": "W"
            }
          },

某種形式的東西

{"nodes":[{"id":'Sint Maarten'},{"id":'Hemisphere'}, {"id": "N"}, {"id":"E"}], "links": [{source:"Sint Maarten", target:"Hemisphere"}, {source:"Hemisphere", target: "N"}, {source: "Hemisphere", target: "E"}]}

所以我可以把它想象成這樣的樹結構

Sint Maarten ---> Hemisphere ---> [N,E]
             ---> Language ---> [Language 1, L2, L3] 

等等。

我嘗試了一種手動方法,我首先將整個 JSON object 數組遞歸地展平為一維並將所有元素添加到節點中,但我一直試圖讓鏈接正確,因為數據的結構方式是key段每個條目都是唯一的。 我試圖有一個樹結構,就像它在所需的 output 中一樣。

我想知道是否有任何技術可以實現這一點,因為我的源 JSON 數組是嵌套的,所以我想讓links算法考慮到嵌套層次結構。 我的源文件,所以我可以為我的整個世界國家數據集生成一個摘要表格。

任何關於如何實現該算法的指針將不勝感激。

編輯:這是我目前的方法

let rawData = fs.readFileSync('./database/factbook.json')
let picker= JSON.parse(rawData)

let arr= {}
arr['name'] = picker['name']
arr['hemisphere'] = [picker['geography']['geographic_coordinates']['latitude']['hemisphere'], picker['geography']['geographic_coordinates']['longitude']['hemisphere']]
arr['area'] = '/'
...
...

我正在嘗試使用我想要的所需 output 創建一個數組,因為原始文件包含 300 多個參數,但我只對其中的 20 個感興趣。 一旦我得到這個數組,我需要將鍵值對轉換為nodelinks結構,這應該考慮到特定鍵的值是數組的情況,例如

key: [a,b,c]

那么我在links中預期的 output 應該是

key --> a
key ---> b
key ---> c

``

歡迎來到堆棧溢出! 這是使用object-scan的更通用的答案,因為您沒有提供太多細節。

您應該可以以此為起點! 請隨時提出任何問題!

 // const lodash = require('lodash'); // const objectScan = require('object-scan'); const data = [{ name: 'Sint Maarten', introduction: { background: '... long text...' }, geography: { location: '... long text...', geographic_coordinates: { latitude: { degrees: 18, minutes: 4, hemisphere: 'N' }, longitude: { degrees: 63, minutes: 4, hemisphere: 'W' } } } }]; const convert = (() => { const logic = { '[*].name': ({ value, context }) => context.nodes.push({ id: value }), '[*].geography.geographic_coordinates.{latitude,longitude}.hemisphere': ({ value, parents, context }) => { context.nodes.push({ id: 'Hemisphere' }); context.nodes.push({ id: value }); context.links.push({ source: parents[parents.length - 2].name, target: 'Hemisphere' }); context.links.push({ source: 'Hemisphere', target: value }); } }; return (haystack) => { const r = objectScan(Object.keys(logic), { breakFn: (kwargs) => { kwargs.matchedBy.forEach((needle) => logic[needle](kwargs)); } })(haystack, { nodes: [], links: [] }); r.nodes = lodash.uniqWith(r.nodes, lodash.isEqual); r.links = lodash.uniqWith(r.links, lodash.isEqual); return r; }; })(); console.log(convert(data)); /* => { nodes: [ { id: 'Hemisphere' }, { id: 'W' }, { id: 'N' }, { id: 'Sint Maarten' } ], links: [ { source: 'Sint Maarten', target: 'Hemisphere' }, { source: 'Hemisphere', target: 'W' }, { source: 'Hemisphere', target: 'N' } ] } */
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/lodash@4.17.20"></script> <script src="https://bundle.run/object-scan@13.9.0"></script>

免責聲明:我是對象掃描的作者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM