Parse a json file with nested indexes and save as csv

独自空忆成欢 提交于 2019-12-11 18:28:31

问题


So, I have a json file with nested indexes. There's an index called "user" which has a subindex called "lang", along with a lot of other subindexes. I only want to extract the "lang" fields out and save it as csv. For the saving as csv part, I can use one of the open source "json2csv" codes, I guess. Could someone help me out with extracting the "lang" fields?


回答1:


Use JSON.stringify() to convert the data into a string, then use match with a RegExp to return an array of specified key/value pairs. Here is an example:

var foo = JSON.stringify({
"Region": {
    "filterField": "kw_Region",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"ApplicationName": {
    "filterField": "kw_ApplicationName",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"IssueType": {
    "filterField": "kw_IssueType",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"Outage": {
    "filterField": "kw_Outage",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"Priority": {
    "filterField": "kw_Priority",
    "filterValues": [
        "aa",
        "bb"
    ]
}
}).match(/(?=filterValues)[^\]]*./g)

console.log(foo) // ["filterValues":["aa","bb"]", "filterValues":["aa","bb"]", "filterValues":["aa","bb"]", "filterValues":["aa","bb"]", "filterValues":["aa","bb"]"]


来源:https://stackoverflow.com/questions/14902466/parse-a-json-file-with-nested-indexes-and-save-as-csv

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