How to extract object from array by json_query? - json

I have got json from variable like below.
[
{
"policyName1": {
"resourceType": "Name1Type",
"id": "uuid-0000-000-0-1",
"extraAttr1":
[
{
"network11":
{
"allowAction": "yes",
"ipAddresses":
[
"192.168.29.193",
"192.168.29.196"
],
"disabled": false,
"ip_protocol": "IPV4_IPV6"
}
}
]
}
},
{
"policyName2": {
"resourceType": "name2Type",
"id": "uuid-0000-000-0-2",
"extraAttr12":
[
{
"network12":
{
"allowAction": "yes",
"ipAddresses":
[
"192.168.29.193",
"192.168.29.197"
],
"disabled": false,
"ip_protocol": "IPV4_IPV6"
}
}
]
}
},
{
"policyName3": {
"resourceType": "name3Type",
"id": "uuid-0000-000-0-3",
"extraAttr2":
[
{
"network13":
{
"allowAction": "yes",
"ipAddresses":
[
"192.168.29.191",
"192.168.29.195"
],
"disabled": false,
"ip_protocol": "IPV4_IPV6"
}
}
]
}
}
]
As you can see it is a normaln json. I need select (extract) whole object by id. For example, when I put id "uuid-0000-000-0-3" i would like receive object PolicyName3
{
"policyName3": {
"resourceType": "name3Type",
"id": "uuid-0000-000-0-3",
"extraAttr3":
[
{
"netowork13":
{
"allowAction": "yes",
"ipAddresses":
[
"192.168.29.191",
"192.168.29.195"
],
"disabled": false,
"ip_protocol": "IPV4_IPV6"
}
}
]
}
}
The digit are add automaticly by software and I can not remove them.
Also it is possible to add extra IP address childName.ipAddresses??
Thank you for help

Q: "Select (extract) the whole object by id."
A: Given the variable policy_list the tasks below
- set_fact:
ext1: "{{ policy_list|
map('dict2items')|list|flatten|
json_query(query)|
items2dict }}"
vars:
id: "uuid-0000-000-0-3"
query: "[?value.id == '{{ id }}']"
- debug:
var: ext1
give
"ext1": {
"policyName3": {
"extraAttr2": [
{
"network13": {
"allowAction": "yes",
"disabled": false,
"ipAddresses": [
"192.168.29.191",
"192.168.29.195"
],
"ip_protocol": "IPV4_IPV6"
}
}
],
"id": "uuid-0000-000-0-3",
"resourceType": "name3Type"
}
}

Related

MongoDB reduce nested

I have a collection of a class that looks something like that:
[
{
"_id": 1,
"title": "dummy title",
"assignments": [
{
"_id": 1,
"name": "a1",
"members": [
{
"_id": 11,
"full_name": "john doe",
"aga": 18
},
{
"_id": 12,
"full_name": "john doe2",
"aga": 18
}
]
}
],
"settings": [
{
"type": "light",
"status": "enabled"
},
{
"type": "flare",
"status": "disabled"
},
{
"type": "toolbar",
"status": "enabled"
}
]
}
]
I have 2 nested documents here "assignments" which have a nested "members"
and "settings". the result i want should look something like that:
{
"_id": 1,
"title": "dummy title",
"assignments": [
{
"_id": 1,
"name": "a1",
"member_ids": [11, 18]
}
],
"active_settings": ["light", "toolbar"]
}
Meaning in each "assignment" I should only return the ids of the members and not the whole member data. and in settings I should only return the settings that are set to "active"
is it possible?
Playground here:
https://mongoplayground.net/p/Le4BdTm_gOv
You can try with $map to go one by one. $mergeObjects helps to merge the output value with same object
[
{
$project: {
title: 1,
assignments: {
$map: {
input: "$assignments",
in: {
$mergeObjects: [
"$$this",
{
members: {
$map: {
input: "$$this.members",
in: "$$this._id"
}
}
}
]
}
}
},
active_settings: {
$reduce: {
input: "$settings",
initialValue: [],
in: {
$cond: [
{
$eq: [
"$$this.status",
"enabled"
]
},
{
$setUnion: [
"$$value",
[
"$$this.type"
]
]
},
"$$value"
]
}
}
}
}
}
]
Working Mongo playground
You can try,
get assignments member ids using $map and $reduce
get active_settings using $reduce
db.collection.aggregate([
{
$project: {
_id: 1,
title: 1,
assignments: {
$map: {
input: "$assignments",
in: {
_id: "$$this._id",
name: "$$this.name",
memberIds: {
$reduce: {
input: "$$this.members",
initialValue: [],
in: { $concatArrays: ["$$value", ["$$this._id"]] }
}
}
}
}
},
active_settings: {
$reduce: {
input: "$settings",
initialValue: [],
in: {
$cond: [
{ $eq: ["$$this.status", "enabled"] },
{ $concatArrays: ["$$value", ["$$this.type"]] },
"$$value"
]
}
}
}
}
}
])
Playground

Ansible-Merge two nested json files into single file of Json format

I am having two json and want to append one into another and save them in one file. I have done a set fact to read the values and put them in a variable using following:
- name: Set json combine to add new event
set_fact:
event_json_create: "{{ lookup('file', 'event_template.json') }}"
- name: Set json combine to get the existing list of events
set_fact:
event_json_existing: "{{ lookup('file', 'notification.json') }}"
Now I want to append the event_json_create to event_json_existing.
The event_json_create looks like this:
"event_json_create": {
"LambdaFunctionConfigurations": [{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [{
"Name": "prefix",
"Value": [
"keying_service/response/"
]
}]
}
},
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:*******:function:xyz"
}]
}
The event_json_existing looks like this:
"event_json_existing": {
"LambdaFunctionConfigurations": [
{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [
{
"Name": "Prefix",
"Value": "staging/inbound/Source_Contact/ac/input_fia/"
}
]
}
},
"Id": "Eventtry",
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:******:function:abc"
}
]
}
How can I append the two json in ansible ensuring that both json are under major group: LambdaFunctionConfigurations and then I can write this into a json file. So the output I expect:
{
"LambdaFunctionConfigurations": [{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [{
"Name": "prefix",
"Value": [
"keying_service/response/"
]
}]
}
},
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:*******:function:xyz"
},
{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [{
"Name": "Prefix",
"Value": "staging/inbound/Source_Contact/ac/input_fia/"
}]
}
},
"Id": "Eventtry",
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:*******:function:abc"
}
]
}
Please help!
This template
shell> cat events.json.j2
{{ events|to_nice_json }}
and the tasks below
- set_fact:
events: "{{ {'LambdaFunctionConfigurations':
([event_json_create.LambdaFunctionConfigurations.0] +
[event_json_existing.LambdaFunctionConfigurations.0])} }}"
- template:
src: events.json.j2
dest: events.json
give
shell> cat events.json
{
"LambdaFunctionConfigurations": [
{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [
{
"Name": "prefix",
"Value": [
"keying_service/response/"
]
}
]
}
},
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:*******:function:xyz"
},
{
"Events": [
"s3:ObjectCreated:*"
],
"Filter": {
"Key": {
"FilterRules": [
{
"Name": "Prefix",
"Value": "staging/inbound/Source_Contact/ac/input_fia/"
}
]
}
},
"Id": "Eventtry",
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:******:function:abc"
}
]
}

Recurse for object if exists in JQ

I have the following structure:
{
"hits":
[
{
"_index": "main"
},
{
"_index": "main",
"accordions": [
{
"id": "1",
"accordionBody": "body1",
"accordionInnerButtonTexts": [
"button11",
"button12"
]
},
{
"id": "2",
"accordionBody": "body2",
"accordionInnerButtonTexts": [
"button21",
"button22"
]
}
]
}
]
}
I want to get to this structure:
{
"index": "main"
}
{
"index": "main",
"accordions":
[
{
"id": "1",
"accordionBody": "body1",
"accordionInnerButtonTexts": [
"button11",
"button12"
]
},
{
"id": "2",
"accordionBody": "body2",
"accordionInnerButtonTexts": [
"button21",
"button22"
]
}
]
}
Which means that I always want to include the _index-field as index, and I want to include the whole accordions-list IF IT EXISTS in the object. Here is my attempt:
.hits[] | {index: ._index, accordions: recurse(.accordions[]?)}
It does not produce what I want:
{
"index": "main",
"accordions": {
"_index": "main"
}
}
{
"index": "main",
"accordions": {
"_index": "main",
"accordions": [
{
"id": "1",
"accordionBody": "body1",
"accordionInnerButtonTexts": [
"button11",
"button12"
]
},
{
"id": "2",
"accordionBody": "body2",
"accordionInnerButtonTexts": [
"button21",
"button22"
]
}
]
}
}
{
"index": "main",
"accordions": {
"id": "1",
"accordionBody": "body1",
"accordionInnerButtonTexts": [
"button11",
"button12"
]
}
}
{
"index": "main",
"accordions": {
"id": "2",
"accordionBody": "body2",
"accordionInnerButtonTexts": [
"button21",
"button22"
]
}
}
It seems to create a list of all different permutations given by mixing the objects. This is not what I want. What is the correct jq command, and what is my mistake?
The problem as stated does not require any recursion. Using your attempt as a model, one could in fact simply write:
.hits[]
| {index: ._index}
+ (if has("accordions") then {accordions} else {} end)
Or, with quite different semantics:
.hits[] | {index: ._index} + . | del(._index)

Update JSON file using PowerShell

I am currently trying to setup a continuous integration system using VSTS and have run into a bit of a snag. As part of the release process I need to update a specific object value in a JSON file depending on the environment. The only tools it seems I have at my disposal that might get this done in the VSTS environment is PowerShell.
I've done quite a bit of research and have not been able to figure out how exactly this can be done. I found this question and answer here on Stack Overflow "How do I update JSON file using PowerShell" but executing the script provided in the answer changes the structure of the JSON file substantially and adds quite a bit of what looks like PowerShell metadata.
Ideally, I would like to take an existing JSON file that gets deployed and update the value of the connectionString property in the example JSON below.
{
"policies": {
"Framework.DataContext": {
"connectionString": "Server=ServerName;Database=DateBaseName;Integrated Security=sspi;"
}
}
}
Does anyone have any advice on how to accomplish this? So far I have tried running the following script but it throws an "The property 'connectionString' cannot be found on this object. Verify that the property exists and can be set." exception. I have verified that the object traversal is correct and the connectionString property exists.
$pathToJson = "D:\Path\To\JSON\file.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.policies.'Framework.DataContext'.connectionString = "Server=ServerName;Database=DateBaseName;Integrated Security=sspi;"
$a | ConvertTo-Json | set-content $pathToJson
The full contents of file.json are as follows
{
"log": {
"level": 0,
"file": "c:\\temp\\simport.log",
"formats": {
"error": null,
"start": null,
"requestBegin": null,
"requestWork": "",
"requestError": null,
"requestEnd": null,
"stop": null
},
"eventLog": {
"name": "Application"
}
},
"diagnostic": {
"stackTrace": false
},
"api": {
"simport": true
},
"roles": {
"0": "Anonymous",
"1": "Administrator",
"2": "Participant",
"3": "Facilitator"
},
"pathType": {
"area": 1,
"region": 2,
"session": 3,
"team": 4
},
"scenarios": {
"default": {
"default": true,
"initState": "Init",
"rounds": [
{
"name": "round1",
"displayName": "R1",
"beginTime": 1,
"endTime": 3
},
{
"name": "round2",
"displayName": "R2",
"beginTime": 4,
"endTime": 6
},
{
"name": "round3",
"displayName": "R3",
"beginTime": 7,
"endTime": 9
},
{
"name": "round4",
"displayName": "R4",
"beginTime": 10,
"endTime": 12
}
]
}
},
"simportQueries": {
"package": "bin/trc.simport3.zip"
},
"customQueries": {
"package": "app/config/custom-queries.zip",
"parameters": {
}
},
"audit": {
"Path.Create": true,
"Path.Delete": true,
"Team.Create": true,
"Team.Update": true,
"Team.Delete": true,
"SimportData.SaveValues": true
},
"tasks": {
"task1": {
"state": "",
"required": "",
"completed": "C:Task1Status:+0"
}
},
"feedback": {
"welcome": {
"text": {
"": "en-us",
"en-us": "Welcome"
}
}
},
"contentCategories": {
"demo1": {
"round": 1
}
},
"policies": {
"Simport.Web.Module": {
"fileMask": ".aspx,.asmx",
"deny": {
"statusCode": 404,
"statusDescription": "Not found",
"location": [
"/{0,1}app/config/(.*\\.json)$",
"/{0,1}app/config/(.*\\.xml)$",
"/{0,1}app/config/(.*\\.zip)$",
"/{0,1}app/config/(.*\\.xlsx)$"
]
},
"formDataContentType": [ "application/x-www-form-urlencoded" ]
},
"Framework.DataContext": {
"connectionString": "Server=(local);Database=Simport3;Integrated Security=sspi;",
"commandTimeout": 30
},
"Simport.Security": {
"passwordEncryption": "",
"passwordSalt": "",
"passwordPolicy": {
"disabled": true,
"min": 8,
"max": 100,
"rules": [
{ "id": "digit", "pattern": "\\d+", "flags": "i" },
{ "id": "letter", "pattern": "\\w+", "flags": "i" },
{ "id": "upper", "pattern": "[A-Z]+" },
{ "id": "lower", "pattern": "[a-z]+" },
{ "id": "special", "pattern": "[\\!##\\$_~]+", "flags": "i" },
{ "id": "prohibited", "pattern": "[\\\\/'\"\\?\\^&\\+\\-\\*\\%\\:;,\\.]+", "flags": "gi", "match": false }
]
}
},
"Simport.PackageDefinition": {
"path": "~/app/config/manifest.xml"
},
"Security.SignIn": {
"result": {
"default": "u,p,p.props,t"
},
"claims": [
[ "userId", "firstName", "lastName" ]
]
},
"Security.GetContext": {
"result": {
"default": "u,p,p.props,pr,t"
}
},
"Security.ChangePassword": {
"allowedRoles": [ 1, 2, 3 ]
},
"Security.ResetPassword": {
"allowedRoles": [ 1, 2 ]
},
"Security.Register": {
"allowedRoles": [ 0 ],
"!pathType-0": 4,
"!roleId-0": 2
},
"Path.Create": {
"allowedRoles": [ 1, 2, 3 ]
},
"Path.Select": {
"allowedRoles": [ 1, 2, 3 ],
"result-1": {
}
},
"Path.Delete": {
"allowedRoles": [ 1, 2 ]
},
"User.Select": {
"allowedRoles": [ 1, 2, 3 ],
"result": {
"select": [ "id", "pathid", "roleid", "name", "email", "login", "props" ],
"restrict": [ "password" ]
},
"result-1": {
"select": "*",
"group": true
}
},
"User.Create": {
"allowedRoles": [ 1, 2 ],
"result": {
"select": [ "id", "pathid", "roleid", "name", "email", "login", "props" ],
"restrict": [ "password" ]
},
"result-1": {
"select": "*",
"group": true
}
},
"User.Update": {
"allowedRoles": [ 1, 2, 3 ],
"result": {
"select": [ "id", "pathid", "roleid", "name", "email", "login", "props" ],
"restrict": [ "password" ]
}
},
"User.Delete": {
"allowedRoles": [ 1, 2 ],
"result": {
"restrict": [ "password" ]
}
},
"Session.Select": {
"allowedRoles": [ 1, 2, 3 ],
"enforcePathLevel": true,
"result": {
"default": [ "name", "beginDate", "endDate" ],
"restrict": [ "password" ]
},
"result-1": {
"default": [ "name", "beginDate", "endDate" ],
"treeAllowed": true,
"treeDefault": false
}
},
"Session.Create": {
"allowedRoles": [ 1, 2 ],
"enforcePathLevel": true
},
"Session.Update": {
"allowedRoles": [ 1, 2 ],
"enforcePathLevel": true,
"update-restictions": [ "password" ],
"update-restictions-1": [ ],
"result": {
"restrict": [ "password" ]
}
},
"Session.Delete": {
"allowedRoles": [ 1, 2 ],
"result": {
"restrict": [ "password" ]
}
},
"Team.Select": {
"allowedRoles": [ 1, 2, 3 ],
"enforcePathLevel": false,
"enforcePathLevel-1": true,
"result-1": {
"treeAllowed": true,
"treeDefault": false
}
},
"Team.Create": {
"allowedRoles": [ 1, 2, 3 ],
"enforcePathLevel": true,
"enforcePathLevel-1": false,
"allowMultiple": false,
"allowMultiple-1": true,
"result": {
},
"overrides": {
"roleID": 3
}
},
"Team.Reset": {
"allowedRoles": [ 1, 2, 3 ]
},
"Team.Delete": {
"allowedRoles": [ 1, 2, 3 ],
"deleteMultiple": true,
"result": {
"default": "t"
}
},
"Team.TransitionTo": {
"allowedRoles": [ 1, 2, 3 ],
"inboundRules": {
"Round1Init": {
"allowedRoles": [ ]
}
},
"outboundRules": {
"Round1Wait": {
"allowedRoles": [ 1, 2, 3 ]
}
}
},
"Team.TakeControl": {
"allowedRoles": [ 1, 2, 3, 4 ],
"select-1": {
"select": "*",
"restrict": [ "ctrl.userID", "ctrl.loginName" ]
}
},
"Team.ReleaseControl": {
"allowedRoles": [ 1, 2, 3, 4 ],
"select-1": {
"select": "*",
"restrict": [ "ctrl.userID", "ctrl.loginName" ]
}
},
"Team.GetStatus": {
"allowedRoles": [ 1, 2, 3 ],
"result": {
"default": "p,t,pr"
}
},
"Data.Select": {
"allowedRoles": [ 1, 2, 3 ]
},
"Data.Update": {
"allowedRoles": [ 1, 2, 3 ],
"audit": {
"g": false,
"i": true,
"o": true,
"s": true
}
},
"Data.ExecuteQuery": {
"allowedRoles": [ 0, 1, 2, 3 ],
"allowed-0": [ "login4\\areas", "login4\\regions", "login4\\sessions", "login4\\teams" ],
"restrict-3": [ "prohibitedQueryNameHere" ]
},
"Document.Select": {
"defaultTextEncoding": "utf-16"
},
"Document.Create": {
"~allowFileExt": [ ],
"denyFileExt": [ ".exe", ".com", ".cmd", ".bat", ".ps1" ],
"~allowContentType": [ ],
"denyContentType": [ "application/x-msdownload" ],
"maxContentLength": 0,
"defaultTextEncoding": "utf-16"
},
"Document.Update": {
"allowedRoles": [ 1, 2, 3 ]
},
"Document.Delete": {
},
"Document.Download": {
}
}
}
Your json is missing the starting and ending curly brackets:
{
"policies": {
"Framework.DataContext": {
"connectionString": "Server=ServerName;Database=DateBaseName;Integrated Security=sspi;"
}
}
}
Now you can update the file like this:
$pathToJson = "F:\Path\To\JSON\file.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.policies.'Framework.DataContext'.connectionString = "Server=ServerName;Database=DateBaseName;Integrated Security=sspi2;"
$a | ConvertTo-Json | set-content $pathToJson
You could also use some Select-Object to get the property:
$connectionString = $a | select -expand policies | select -expand Framework.DataContext
$connectionString.connectionString = 'Test'
$s = Get-Content "F:\Path\To\JSON\file.json" -Raw|ConvertFrom-Json
$s.policies.'Framework.DataContext'.connectionString="Server=ServerName;Database=DateBaseName;Integrated Security=sspi2;"
$s|ConvertTo-Json |Set-Content "F:\Path\To\JSON\file.json"
I also faced the similar problem. Fixed it by specifying the INDEX of the object I was trying to edit.
$a.policies[0].'Framework.DataContext'.connectionString = "Server=ServerName;Database=DateBaseName;Integrated Security=sspi;"
Hope it helps!

How to parse JSON string and check if result contains the text, then ignore or allow it?

I'm working on a Minecraft launcher, I have a problem, because my launcher uses the original way, and for example, here is the JSON:
{
"id": "1.8.1",
"time": "2014-11-24T14:13:31+00:00",
"releaseTime": "2014-11-24T14:13:31+00:00",
"type": "release",
"minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory} --assetsDir ${assets_root} --assetIndex ${assets_index_name} --uuid ${auth_uuid} --accessToken ${auth_access_token} --userProperties ${user_properties} --userType ${user_type}",
"minimumLauncherVersion": 14,
"assets": "1.8",
"libraries": [
{
"name": "com.ibm.icu:icu4j-core-mojang:51.2"
},
{
"name": "net.sf.jopt-simple:jopt-simple:4.6"
},
{
"name": "com.paulscode:codecjorbis:20101023"
},
{
"name": "com.paulscode:codecwav:20101023"
},
{
"name": "com.paulscode:libraryjavasound:20101123"
},
{
"name": "com.paulscode:librarylwjglopenal:20100824"
},
{
"name": "com.paulscode:soundsystem:20120107"
},
{
"name": "io.netty:netty-all:4.0.23.Final"
},
{
"name": "com.google.guava:guava:17.0"
},
{
"name": "org.apache.commons:commons-lang3:3.3.2"
},
{
"name": "commons-io:commons-io:2.4"
},
{
"name": "commons-codec:commons-codec:1.9"
},
{
"name": "net.java.jinput:jinput:2.0.5"
},
{
"name": "net.java.jutils:jutils:1.0.0"
},
{
"name": "com.google.code.gson:gson:2.2.4"
},
{
"name": "com.mojang:authlib:1.5.17"
},
{
"name": "com.mojang:realms:1.7.5"
},
{
"name": "org.apache.commons:commons-compress:1.8.1"
},
{
"name": "org.apache.httpcomponents:httpclient:4.3.3"
},
{
"name": "commons-logging:commons-logging:1.1.3"
},
{
"name": "org.apache.httpcomponents:httpcore:4.3.2"
},
{
"name": "org.apache.logging.log4j:log4j-api:2.0-beta9"
},
{
"name": "org.apache.logging.log4j:log4j-core:2.0-beta9"
},
{
"name": "org.lwjgl.lwjgl:lwjgl:2.9.1",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "org.lwjgl.lwjgl:lwjgl_util:2.9.1",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "org.lwjgl.lwjgl:lwjgl-platform:2.9.1",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
},
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "net.java.jinput:jinput-platform:2.0.5",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
},
{
"name": "tv.twitch:twitch:6.5"
},
{
"name": "tv.twitch:twitch-platform:6.5",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "linux"
}
}
],
"natives": {
"linux": "natives-linux",
"windows": "natives-windows-${arch}",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
},
{
"name": "tv.twitch:twitch-external-platform:4.5",
"rules": [
{
"action": "allow",
"os": {
"name": "windows"
}
}
],
"natives": {
"windows": "natives-windows-${arch}"
},
"extract": {
"exclude": [
"META-INF/"
]
}
}
],
"mainClass": "net.minecraft.client.main.Main"
}
So, in the "libraries" [, the game libraries listed with "name":, and below, the libraries contains the rules that apply to them, I want to know this rules with the library file name, and apply the actions with it, but I don't have any idea, I using this code, but this only redirect the libraries.
Here is my code:
Dim item As String = Version
Dim client As New WebClient()
Await client.DownloadFileTaskAsync(New Uri("https://s3.amazonaws.com/Minecraft.Download/versions/" + item + "/" + item + ".json"), Root + "\versions\" + item + "\" + item + ".json")
Dim JSONREADER As New StreamReader(Root + "\versions\" + item + "\" + item + ".json")
json = JSONREADER.ReadToEnd()
JSONREADER.Close()
Dim JSONResult As Object = JsonConvert.DeserializeObject(Of Object)(json)
MinecraftArgs = JSONResult("minecraftArguments")
AssetIndex = JSONResult("assets")
MainClass = JSONResult("mainClass")
For Each i In JSONResult("libraries").Children()
LibrariesList.Add(i.ToObject(Of MClibraries).name)
Next
For example:
{
"name": "org.lwjgl.lwjgl:lwjgl:2.9.1",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
The "name" as the name of the file, the "rules" there is two action: allow, disallow, under the disallow, there is the "os":, this sets the action, because
"os": {
"name": "osx"
}
this only allows the file in Windows and Linux, but disallows the file in mac OS X, so I want to get and apply this actions.
I want to add these libraries:
"libraries": [
{
"name": "com.ibm.icu:icu4j-core-mojang:51.2"
},
{
"name": "net.sf.jopt-simple:jopt-simple:4.6"
},
{
"name": "com.paulscode:codecjorbis:20101023"
},
{
"name": "com.paulscode:codecwav:20101023"
},
{
"name": "com.paulscode:libraryjavasound:20101123"
},
{
"name": "com.paulscode:librarylwjglopenal:20100824"
},
{
"name": "com.paulscode:soundsystem:20120107"
},
{
"name": "io.netty:netty-all:4.0.23.Final"
},
{
"name": "com.google.guava:guava:17.0"
},
{
"name": "org.apache.commons:commons-lang3:3.3.2"
},
{
"name": "commons-io:commons-io:2.4"
},
{
"name": "commons-codec:commons-codec:1.9"
},
{
"name": "net.java.jinput:jinput:2.0.5"
},
{
"name": "net.java.jutils:jutils:1.0.0"
},
{
"name": "com.google.code.gson:gson:2.2.4"
},
{
"name": "com.mojang:authlib:1.5.17"
},
{
"name": "com.mojang:realms:1.7.5"
},
{
"name": "org.apache.commons:commons-compress:1.8.1"
},
{
"name": "org.apache.httpcomponents:httpclient:4.3.3"
},
{
"name": "commons-logging:commons-logging:1.1.3"
},
{
"name": "org.apache.httpcomponents:httpcore:4.3.2"
},
{
"name": "org.apache.logging.log4j:log4j-api:2.0-beta9"
},
{
"name": "org.apache.logging.log4j:log4j-core:2.0-beta9"
},
And add these libraries if the rules allow Windows operating system:
{
"name": "org.lwjgl.lwjgl:lwjgl:2.9.1",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "org.lwjgl.lwjgl:lwjgl_util:2.9.1",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "org.lwjgl.lwjgl:lwjgl-platform:2.9.1",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
},
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "osx"
}
}
]
},
{
"name": "net.java.jinput:jinput-platform:2.0.5",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
},
{
"name": "tv.twitch:twitch:6.5"
},
{
"name": "tv.twitch:twitch-platform:6.5",
"rules": [
{
"action": "allow"
},
{
"action": "disallow",
"os": {
"name": "linux"
}
}
],
"natives": {
"linux": "natives-linux",
"windows": "natives-windows-${arch}",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
},
{
"name": "tv.twitch:twitch-external-platform:4.5",
"rules": [
{
"action": "allow",
"os": {
"name": "windows"
}
}
],
"natives": {
"windows": "natives-windows-${arch}"
},
"extract": {
"exclude": [
"META-INF/"
]
}
}
],
If in the rules only disallow, and in the disallow only for example OS X, this means the Windows, and the Linux allowed.
First edit your MClibraries class so that it looks like this:
Public Class MClibraries
Public name As String
Public rules As JArray
End Class
So to do what you're asking I start off with a list and a dictionary:
Private ReadOnly _librariesList As New List(Of String)
Private ReadOnly _disallowed As New Dictionary(Of String, String)
NOTE: You already have _librariesList, but yours is named LibrariesList.
Next, to get the libraries, I did this:
Dim item As String = Version
Dim client = New WebClient() With {.Proxy = Nothing}
Dim json = Await client.DownloadStringTaskAsync(New Uri(String.Format("http://s3.amazonaws.com/Minecraft.Download/versions/{0}/{0}.json", item)))
Dim jsonResult As Object = JsonConvert.DeserializeObject(Of Object)(json)
For Each i In jsonResult("libraries")
Dim entry As MClibraries = i.ToObject(Of MClibraries)() ' Converts object to MClibrary
_librariesList.Add(entry.name) ' Add the name of each entry to the listbox
If Not IsNothing(entry.rules) AndAlso entry.rules.Count = 2 Then ' Check to make sure it isn't empty
_disallowed.Add(entry.rules(1)("os")("name")) ' Gets the os that is disallowed
End If
Next
NOTE: Just add what you already have to this
Now you can access all the disallowed os's with the new dictionary "_disallowed". The key is the os that is disallowed and the value is the package.
If you want to see if the os matches the user os you can write the following. Also you will need to add the reference to System.Management and import it as well
Private _currentOs as String
'The following should go under the loading of a form
Dim osname As String = (From x In New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType(Of ManagementObject)()
Select x.GetPropertyValue("Caption")).FirstOrDefault()
'The following should go where you retrieve the libraries
For Each i In jsonResult("libraries")
Dim entry As MClibraries = i.ToObject(Of MClibraries)() ' Converts object to MClibrary
If Not IsNothing(entry.rules) AndAlso entry.rules.Count = 2 Then ' Check to make sure it isn't empty
If Not _currentOs.ToLower.Contains(entry.rules(1)("os")("name")) Then
_librariesList.Add(entry.name)
End If
End If
Next