简体   繁体   English

从javascript中的json中提取子集

[英]Extract subset from json in javascript

I would like to substract json entries from the main JSON bulk data, based on an input, in JavaScript. 我想基于JavaScript中的输入从主要JSON批量数据中减去JSON条目。 Each entry in the main JSON data has it's own unique ID, but the filter should be based on the text identifier rather than the ID. JSON主数据中的每个条目都有其自己的唯一ID,但过滤器应基于文本标识符而不是ID。 I would like to retrieve for example all entries that contain the word burg ( Burg , BURG , bUrg , etc.) or any other given variety. 我想检索例如包含burgBurgBURGbUrg等)或任何其他给定bUrg所有条目。 This should of course also work with other search terms. 当然,这也应与其他搜索词一起使用。 I do not possess the JavaScript skills to do this. 我不具备执行此操作的JavaScript技能。

In the data given below this should return 3 results. 在下面给出的数据中,这将返回3个结果。 Obviously, the result should be the exact same JSON format. 显然,结果应为完全相同的JSON格式。

Example JSON: JSON示例:

{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}

Do not use JavaScript for this. 请勿为此使用JavaScript。 Use SQL and its LIKE operator instead. 请改用SQL及其LIKE运算符。

But if you insist on using JavaScript for this… 但是,如果您坚持为此使用JavaScript……

Just like HTML , regular expressions cannot fully parse JSON because of serialization. 就像HTML一样,由于序列化,正则表达式无法完全解析JSON。

Filtering after JSON.parse is quite easy however; 但是,在JSON.parse之后进行过滤非常容易。 you can use the Array.prototype.filter() method: 您可以使用Array.prototype.filter()方法:

 var s = '{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}'; var input = "burg"; var o = JSON.parse(s); o.features = o.features.filter(e => RegExp(input, 'i').test(e.text)); console.log(JSON.stringify(o)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM