uncommon

Json Remove key

4 posts in this topic

So I started using Json.au3 (2015.01.08) by Ward. Pretty good but I am having some real trouble figuring out how to remove a certain key.

There is an internal function called Json_ObjDelete which seems to use a Scripting.Dictionary Object this uses $Object.Remove($Key)

but this will only remove the first level key. For example if I use $Object.Remove('foo') in a json string like this...

{"foo":"foo","bar":["bar"],"test":["",{"foo":{"bar":["","",{"foo":{"bar":"Test"}}]}}]}

It will reduce do this...

{"bar":["bar"],"test":["",{"foo":{"bar":["","",{"foo":{"bar":"Test"}}]}}]}

So my question is how do I get to the next 'foo' and remove it because it does not seem to recognize others as a key?

Thank you for your time.


No problem can withstand the assault of sustained thinking.Voltaire

_Array2HTMLTable()_IEClassNameGetCollection()_IEquerySelectorAll()

Share this post


Link to post
Share on other sites



I'm not really familiar with json or that .au3, but could you do something hacky like:

Local $sJSON = '{"foo":"foo","bar":["bar"],"test":["",{"foo":{"bar":["","",{"foo":{"bar":"Test"}}]}}]}'
ConsoleWrite ( $sJSON & @CRLF )
$sJSON = StringRegExpReplace ( $sJSON, '"foo"[,:]', '' )
$sJSON = StringRegExpReplace ( $sJSON, '"foo"', '' )
ConsoleWrite ( "Deleted: " & $sJSON & @CRLF )

 

Share this post


Link to post
Share on other sites

That could work for this example but I need to be able to delete any part of if. There might be some 'foo' I want to remove and some I want to keep.

I am starting to think it might be a easier to use autoit as a wrapping in another language.


No problem can withstand the assault of sustained thinking.Voltaire

_Array2HTMLTable()_IEClassNameGetCollection()_IEquerySelectorAll()

Share this post


Link to post
Share on other sites

Figured it out. Use the key name in the object to get the next level object, if you do not know what will be in the next object and you need to iterate use the Keys function like this $Object.keys to return an array of the nested keys. When you get the final Parent object of the key you want to remove I used the builtin Json_ObjDelete function to remove the target key and value.

The Sample code below removes the bOpts Key and value. Hopefully this helps someone in the future.

Sample Code

$sJsonString = FileRead(@DesktopDir & "\codebeautify.json")
    $oJsonString = Json_Decode($sJsonString)
    $oItems = $oJsonString("Game")
    $oParts = $oItems("Interface")
    $oMenu = $oParts("MainMenu")
    $aMenu = $oMenu.keys
    _ArrayDisplay($aMenu)
    Json_ObjDelete($oMenu, "bOpts")

Sample Json

{
"Game":{
   "Name":"Game Title Goes Here",
   "Interface":{
      "MainMenu":{
         "bOpts":"Options",
         "bMp":"MultiPlayer",
         "bSp":"SinglePlayer",
         "bCreds":"Credits",
         "bQuit":"Quit Game"
      }
   }
   "Input":{
      "inMouse":"Mouse",
      "inJoy":"Joy Stick",
      "inKeys":"KeyBoard"
   }
}
"key2":"Key2 Text",
"key3":"Key3 Text",
"key4":"Key4 Text",
"num":1024,
"digits":{"1","2","3","4"}
}

 


No problem can withstand the assault of sustained thinking.Voltaire

_Array2HTMLTable()_IEClassNameGetCollection()_IEquerySelectorAll()

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • sivaramanm
      WinHTTP Send with Complex Send Parameters
      By sivaramanm
      Have this following input parameter(Complex list of inputs) that need to be SEND as part of HTTP POST Request. 
      Have been searching forums to find an AutoIT equivalent to enapsulate the following data, but unsuccessful.
      Below given Working Code is failing with 400-Bad Request for obvious reason of incomplete input - unable to send ip_list and other array type parameters
      Questions:
      1. How to encapsulate the below given data for $oHttp.Send()
      2. How to enapsulate special data types like
       null - aligned_device_tempate parameter
      White sapced values - () and
      empty array? - hostname or device_groups
       
      Input Parameter in JSON format to be converted & sent in AutoIT compatible
      {       "name": "SnmpSIM",       "description": "EM7 device created by BDD test case",       "credentials":"{{feature.credential.body.result_set[*].URI}}",        "organization": "/api/organization/0",       "aligned_device_template": null,       "aligned_collector": "{{feature.appliance_id[0].id[0]}}{{feature.appliance_id[0].id[1]}}",       "discover_non_snmp": "1",       "scan_ports": [         "21",         "22",         "23",         "25",         "80"       ],       "ip_lists": [         {         "start_ip": "{{feature.json.ip}}",         "end_ip": "{{feature.json.ip}}"         }       ],       "dhcp_enabled": "0",       "duplicate_protection": "1",       "model_device": "1",       "log_all": "1",       "scan_all_ips": null,       "port_scan_timeout": null,       "initial_scan_level": null,       "scan_throttle": null,       "interface_inventory_timeout": "600000",       "max_interface_inventory_count": "10000",       "bypass_interface_inventory": "0",       "hostnames": [],       "device_groups": []     }  
      Working Code
      ; The data to be sent $sPD = 'name=SnmpSIM&description=EM7 device created by BDD test case&credentials=37&organization=/api/organization/0&aligned_device_template=null&aligned_collector=1&discover_non_snmp=1&dhcp_enabled=0&duplicate_protection=1&model_device=1&log_all=1&scan_all_ips= null&port_scan_timeout= null&initial_scan_level= null&scan_throttle= null&interface_inventory_timeout=600000&max_interface_inventory_count=10000&bypass_interface_inventory=0&hostnames=&device_groups=&scan_ports=21' ; Creating the object $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", "http://10.2.4.18/api/discovery_session", False) $oHTTP.SetCredentials("username","password",0) $oHTTP.SetRequestHeader("Content-Type", "application/em7-resource-uri") ; Performing the Request $oHTTP.Send($sPD) ; Download the body response if any, and get the server status response code. $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then  MsgBox(4096, "Response code", $oStatusCode) EndIf ; Saves the body response regardless of the Response code  $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists  FileWrite($file, $oReceived)  FileClose($file)  

       SAMPLE VBA CODE for Reference
       Dim Items As New Collection  Dim Item As Dictionary  Dim Id As Long  For Id = 1 To 2      Set Item = New Dictionary      Item("iditem") = Id      Item("amount") = 1      Items.Add Item  Next Id  Request.AddBodyParameter "id", 5633  Request.AddBodyParameter "items", Items $oDictionary = ObjCreate("Scripting.Dictionary") $oDictionary.ADD("start_ip", "10.20.7.31") $oDictionary.ADD("end_ip", "10.20.7.33")  
    • Altor
      Curl, JSON and CouchDB sintax error
      By Altor
      Hi all:
      I have a small problem with Curl syntax to send a POST to a CouchDB database.
      I want send this:
      -H Content-type: application/json -X POST http://127.0.0.1:5984/test -d {"title": "pencil"} but this code does not work:
      $code ='curl.exe -H Content-type: application/json -X POST http://127.0.0.1:5984/test -d {"title": "pencil"}' Run(@ComSpec & " /k " & $code,"",@SW_HIDE) but to work I have to format the line like this:
      $code = 'curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d "{\"title\":\"pencil\"}"' Run(@ComSpec & " /k " & $code,"",@SW_HIDE) my question is whether this is the most correct way to write the correct code using the additional signs "  and  \   or is there some other more elegant way to do the same.
      Thank's
    • Ward
      MessagePack UDF
      By Ward
      Introduction
      "MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller." (by http://msgpack.org/).
      There are already so many languages support MessagePack format, here comes AutoIt version. The backend coder is Charlie Gunyon's cmp. It supported MessagePack proposal v5.
      This UDF only have two public functions: MsgPack_Pack() and MsgPack_Unpack(). It just like Json_Enocde() and Json_Decode() in my ?do=embed' frameborder='0' data-embedContent>>JSON UDF. The Map type will  be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). So I suggest using Json.au3 to deal with the Map/Object data type. The main difference is MessagePack support Binary format, but Json not. For example (?do=embed' frameborder='0' data-embedContent>>Json.au3 is required to run this example):
      Local $Obj1 Json_Put($Obj1, ".binary", Binary("0x00")) Json_Put($Obj1, ".string", "abc") Json_Put($Obj1, ".int", Random(0, 1000, 1)) Json_Put($Obj1, ".float", Random()) Json_Put($Obj1, ".bool", True) Json_Put($Obj1, ".null", Null) Local $Binary = MsgPack_Pack($Obj1) Local $Obj2 = MsgPack_Unpack($Binary) ConsoleWrite("Test2 $Obj1.binary is " & VarGetType(Json_Get($Obj2, ".binary")) & @LF) ; "Binary" In my opinion, for human readable data storing or exchanging, of course choose Json. Otherwise, especially to exchange data on the internet, MessagePack may be a better choice. 
      MsgPack.zip
    • Ward
      A Non-Strict JSON UDF (JSMN)
      By Ward
      Introduction
      JSON (Javascript Object Notation) is a popular data-interchange format and supported by a lot of script languages. On AutoIt, there is already a >JSON UDF written by Gabriel Boehme. It is good but too slow, and not supports unicode and control characters very well. So I write a new one (and of course, fast one as usual).

      I use a machine code version of JSON parser called "jsmn". jsmn not only supports standard JSON, but also accepts some non-strict JSON string. See below for example.
       
      Important Update!!
      I rename the library from jsmn.au3 to json.au3. All function names are changed, too.
       
      Decoding Function
      Json_Decode($Json) $Json can be a standard or non-standard JSON string. For example, it accepts:
      { server: example.com port: 80 message: "this looks like a config file" } The most JSON data type will be decoded into corresponding AutoIt variable, including 1D array, string, number, true, false, and null. JSON object will be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). AutoIt build-in functions like IsArray, IsBool, etc. can be used to check the returned data type. But for Object and Null, Json_IsObject() and Json_IsNull() should be used.

      If the input JSON string is invalid, @Error will be set to $JSMN_ERROR_INVAL. And if the input JSON string is not finish (maybe read from stream?), @Error will be set to $JSMN_ERROR_PART.

      Encoding Function
      Json_Encode($Data, $Option = 0, $Indent = "\t", $ArraySep = ",\r\n", $ObjectSep = ",\r\n", $ColonSep = ": ") $Data can be a string, number, bool, keyword(default or null), 1D arrry, or "Scripting.Dictionary" COM object. Ptr will be converted to number, Binary will be converted to string in UTF8 encoding. Other unsupported types like 2D array, dllstruct or object will be encoded into null.

      $Option is bitmask consisting following constant:
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f) $JSON_UNESCAPED_UNICODE ; Encode multibyte Unicode characters literally $JSON_UNESCAPED_SLASHES ; Don't escape / $JSON_HEX_TAG ; All < and > are converted to \u003C and \u003E $JSON_HEX_AMP ; All &amp;amp;amp;amp;s are converted to \u0026 $JSON_HEX_APOS ; All ' are converted to \u0027 $JSON_HEX_QUOT ; All " are converted to \u0022 $JSON_PRETTY_PRINT ; Use whitespace in returned data to format it $JSON_STRICT_PRINT ; Make sure returned JSON string is RFC4627 compliant $JSON_UNQUOTED_STRING ; Output unquoted string if possible (conflicting with $JSMN_STRICT_PRINT) Most encoding option have the same means like PHP's json_enocde() function. When $JSON_PRETTY_PRINT is set, output format can be change by other 4 parameters ($Indent, $ArraySep, $ObjectSep, and $ColonSep). Because these 4 output format parameters will be checked inside Jsmn_Encode() function, returned string will be always accepted by Jsmn_Decode(). $JSON_UNQUOTED_STRING can be used to output unquoted string that also accetped by Jsmn_Decode().

      $JSON_STRICT_PRINT is used to check output format setting and avoid non-standard JSON output. So this option is conflicting with $JSON_UNQUOTED_STRING.

      Get and Put Functions
      Json_Put(ByRef $Var, $Notation, $Data, $CheckExists = False) Json_Get(ByRef $Var, $Notation) These functions helps user to access object or array more easily. Both dot notation and square bracket notation can be supported. Json_Put() by default will create non-exists objects and arrays. For example:
      Local $Obj Json_Put($Obj, ".foo", "foo") Json_Put($Obj, ".bar[0]", "bar") Json_Put($Obj, ".test[1].foo.bar[2].foo.bar", "Test") Local $Test = Json_Get($Obj, '["test"][1]["foo"]["bar"][2]["foo"]["bar"]') ; "Test" Object Help Functions
      Json_ObjCreate() Json_ObjPut(ByRef $Object, $Key, $Value) Json_ObjGet(ByRef $Object, $Key) Json_ObjDelete(ByRef $Object, $Key) Json_ObjExists(ByRef $Object, $Key) Json_ObjGetCount(ByRef $Object) Json_ObjGetKeys(ByRef $Object) Json_ObjClear(ByRef $Object) These functions are just warps of "Scripting.Dictionary" COM object. You can use these functions if you are not already familiar with it.
       
      == Update 2013/05/19 ==
       
      * Add Jsmn_Encode() option "$JSMN_UNESCAPED_ASCII". Now the default output of Json_Encode() is exactly the same as PHP's json_encode() function (for example, chr(1) will be encoded into u0001).
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f)  
      == Update 2015/01/08 ==
      * Rename the library from jsmn.au3 to json.au3. All function names are changed, too.
      * Add Json_Put() and Json_Get()
      * Add Null support
      * Using BinaryCall.au3 to loading the machine code.

      JSMN.zip
      JSMN.zip
      Json.zip
    • redrider81
      Idea: Feature Rich REST UDF
      By redrider81
      There are some impressive UDFs emerging or being re-written recently surrounding REST services. At the same time, the explosion of useful web services and use-cases to tie them together shows no signs of slowing. I suggest a project to tie together the existing UDFs into a more comprehensive UDF which abstracts the four major functions of working with REST services: 
      Authentication (OAuth1/2, OpenID/Connect, Etc) The HTTP Calls (Flexibility with URL, HTTP Methods, Header, Body) Manipulating the Data (XML and JSON) Local Storage/Caching (A new file-based NoSQL Strategy combined with SQLite) Some of these are pretty tall orders, however the overall notion seems so universally useful with the present technologies, I wanted to suggest it for community feedback to measure support. 
      Full disclosure, I don't have time or skill level to contribute to these UDF's in a meaningful way. I thought maybe I shouldn't even post this for that reason, but I went ahead anyway. 
      The UDFs that I find exciting and think would be good candidates for inclusion are listed below: