我有大量的JSON架构(不是JSON数据),并希望从中提取密钥。
我有如下所示的示例JSON模式。由于它的大小,我不能发布实际的模式。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"id": "http://example.com/example.json",
"properties": {
"checked": {
"id": "/properties/checked",
"type": "boolean"
},
"id": {
"id": "/properties/id",
"type": "integer"
},
"name": {
"id": "/properties/name",
"type": "string"
},
"price": {
"id": "/properties/price",
"type": "number"
},
"tags": {
"id": "/properties/tags",
"items": {
"id": "/properties/tags/items",
"type": "string"
},
"type": "array"
}
},
"type": "object"
}
根据这个模式,我将如何能够提取密钥,如下面的JSON所示。下面的JSON对象是JSON数据,其中包含JSON模式中提到的所有密钥。
{
"id": 1,
"name": "A green door",
"price": 12.5,
"checked": false,
"tags": [
"home",
"green"
]
}
我已经尝试了 JSON架构faker 但每次都会产生不同的数据。它甚至会产生空对象,而我无法手动修改JSON架构。我希望所有钥匙都在那里。例如,在上面的模式中,我应该能够提取下面的所有键。
ID
名称
价
检查
标签
家
绿色
我尝试了递归解决方案,但这没有帮助。我将如何构建JSON数据的任何解决方案,其中包含使用JavaScript
在架构中提到的所有键答案 0 :(得分:0)
您可以尝试以下操作。我希望这可以帮助您实现用例。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class regexExample {
public static void main(String[] args){
String jsonstr="{\n" +
" \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" +
" \"definitions\": {},\n" +
" \"id\": \"http://example.com/example.json\",\n" +
" \"properties\": {\n" +
" \"checked\": {\n" +
" \"id\": \"/properties/checked\",\n" +
" \"type\": \"boolean\"\n" +
" },\n" +
" \"id\": {\n" +
" \"id\": \"/properties/id\",\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"name\": {\n" +
" \"id\": \"/properties/name\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"price\": {\n" +
" \"id\": \"/properties/price\",\n" +
" \"type\": \"number\"\n" +
" },\n" +
" \"tags\": {\n" +
" \"id\": \"/properties/tags\",\n" +
" \"items\": {\n" +
" \"id\": \"/properties/tags/items\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"type\": \"array\"\n" +
" }\n" +
" },\n" +
" \"type\": \"object\"\n" +
"}";
Pattern p = Pattern.compile("\"[\\w]+\":");
Matcher m = p.matcher(jsonstr);
String result="";
while (m.find( )) {
result = m.group().replace("\"","");
result = result.replace(":","");
System.out.println("Found value: " + result );
}
}
}
答案 1 :(得分:0)
function myFunction() {
var str = { "$schema": "http://json-schema.org/draft-04/schema#", "definitions": {}, "id": "http://example.com/example.json", "properties": { "checked": { "id": "/properties/checked", "type": "boolean" }, "id": { "id": "/properties/id", "type": "integer" }, "name": { "id": "/properties/name", "type": "string" }, "price": { "id": "/properties/price", "type": "number" }, "tags": { "id": "/properties/tags", "items": { "id": "/properties/tags/items", "type": "string" }, "type": "array" } }, "type": "object"};
for (var key in str) {
console.log(key);
for(var key1 in key) {
console.log(key);
}
}
}
这将获得密钥的关键。如果你想获得所有密钥,那么你需要编写递归方法。