Jump to content

Step through and rewrite Json


Recommended Posts

Below is a sample output from xteve.  Xteve is used to pass streams from an HDHomeRun, modify them, then pass to plex.  When doing testing, I frequently have to rebuild my config, and readd the icons and such.  I would like to use auto it to step through the Json and take certain actions.  But, I do not know the best way to target each line.

 

Obviously, I do not know a ton about the json structure, but each element or section represents a single channel.  So I would want to do something like this...

 

If "name" contains "Fox 2" Then...

"x-update-channel-icon" = True
    "x-update-channel-name" = True

then anytime I need to rebuild, I can just execute the script.  

 

Any help would be appreciated.  Thanks

 

 

 

 

"x-ID.0": {
    "_file.m3u.id": "MK5LHDCC78UBXBVV9K1W",
    "_file.m3u.name": "File",
    "_file.m3u.path": "/root/.xteve/data/MK5LHDCC78UBXBVV9K1W.m3u",
    "group-title": "",
    "name": "Fox 2 KTVI",
    "tvg-id": "fox2ktvi.us",
    "tvg-logo": "",
    "tvg-name": "",
    "url": "",
    "_uuid.key": "",
    "_values": "",
    "x-active": false,
    "x-category": "",
    "x-channelID": "1000",
    "x-epg": "x-ID.0",
    "x-group-title": "",
    "x-mapping": "-",
    "x-xmltv-file": "-",
    "x-name": "Fox 2 KTVI | HD",
    "x-update-channel-icon": false,
    "x-update-channel-name": false,
    "x-description": ""
  },

"x-ID.1": {
    "_file.m3u.id": "MK5LHDCC78UBXBVV9K1W",
    "_file.m3u.name": "File",
    "_file.m3u.path": "/root/.xteve/data/MK5LHDCC78UBXBVV9K1W.m3u",
    "group-title": "",
    "name": "CBS 4 KMOV",
    "tvg-id": "kmov4.us",
    "tvg-logo": "",
    "tvg-name": "",
    "url": "",
    "_uuid.key": "",
    "_values": "",
    "x-active": false,
    "x-category": "",
    "x-channelID": "1000",
    "x-epg": "x-ID.0",
    "x-group-title": "",
    "x-mapping": "-",
    "x-xmltv-file": "-",
    "x-name": "CBS 4 | HD",
    "x-update-channel-icon": false,
    "x-update-channel-name": false,
    "x-description": ""
  },

Link to post
Share on other sites

Something like this?

 

$sJSON = ClipGet() ;This is the json string

$aRet = StringRegExp($sJSON, '(?s)("[^"]+": {.*?})', 3)
$sFind = 'Fox 2'

For $sStr In $aRet
    If StringRegExp($sStr, '"name": ".*' & $sFind & '.*",') Then
        $sRep = StringRegExpReplace($sStr, '("x-update-channel-icon": )false', '\1true')
        $sRep = StringRegExpReplace($sRep, '("x-update-channel-name": )false', '\1true')
        $sJSON = StringReplace($sJSON, $sStr, $sRep)
    EndIf
Next

ConsoleWrite($sJSON & @CRLF)

 

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to post
Share on other sites

Or using UDF :

#include <Constants.au3>
#include <json.au3>

$data = FileRead("Test2.json")
$json_data = json_decode($data)
If @error Then Exit MsgBox(0, "decode", @error)

;Json_Dump($data)

Local $value
For $x = 1 To 3 Step 2
  $value = json_get($json_data, "[" & $x & "][name]")
  If @error Then Exit MsgBox(0, "get", @error)
  If StringInStr($value, "Fox 2") Then
    json_put($json_data, "[" & $x & "][x-update-channel-icon]", "True")
    json_put($json_data, "[" & $x & "][x-update-channel-name]", "True")
  EndIf
Next

ConsoleWrite (Json_Encode_Pretty($json_data, 0, "  ", @CRLF, "," & @CRLF, ": ") & @CRLF)

 

Link to post
Share on other sites

There exists also a json-processor UDF for manipulate json: jq-udf

Admittedly, the syntax is not very intuitive, but this is how it could work with this UDF:

#include "jq.au3"

$data = FileRead("Test2.json")

_jqInit()
$sCmdOutput = _jqExec($data, '.[] | (objects | select(.name | contains("Fox 2")) | ."x-update-channel-icon" = true) // . ')

ConsoleWrite($sCmdOutput)

 

Link to post
Share on other sites
7 hours ago, Nine said:

Or using UDF

Which one?

I have tried few, but on the fragment from the first post they are not working.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to post
Share on other sites
1 hour ago, MrCreatoR said:

Which one?

I have tried few, but on the fragment from the first post they are not working.

Did you try Chilkat.au3 UDF ?
JSON if free componet in Chilkat.

 

Signature beginning:
Please remember: "AutoIt".....  Wondering who uses AutoIt and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
Include Dependency Tree (Tool for analyzing script relations)
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) *

PDF Related:How to get reference to PDF object embeded in IE *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2021-03-17

Link to post
Share on other sites
  • Developers
2 hours ago, MrCreatoR said:

I have tried few, but on the fragment from the first post they are not working.

Guess that is because the fragment isn't a valid JSON as posted and is missing the opening and closing brackets. 

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites
11 hours ago, AspirinJunkie said:

There exists also a json-processor UDF for manipulate json: jq-udf

Admittedly, the syntax is not very intuitive, but this is how it could work with this UDF:

#include "jq.au3"

$data = FileRead("Test2.json")

_jqInit()
$sCmdOutput = _jqExec($data, '.[] | (objects | select(.name | contains("Fox 2")) | ."x-update-channel-icon" = true) // . ')

ConsoleWrite($sCmdOutput)

 

First, thank you for mentioning jq.

The only issue with your example is that the result will only be the selected keys' object values without their keys.  If I understood the OP correctly, the result should be a complete, modified json configuration file.  The example below, using jq, shows one way to replace just the specified values while leaving the rest of the data as-is.  For brevity, I've condensed the json source but kept the relevant fields.  I have also assumed that the original json snippet was of a json object with multiple key/value pairs.  If it was supposed to be an array of json objects, it would be a simple modification to the jq filter to get the required result.

#cs
    This example uses the jq UDF.
    https://www.autoitscript.com/forum/files/file/502-jq-udf-a-powerful-flexible-json-processor/
#ce

#include <Constants.au3>
#include <jq.au3> ;<== Modify as needed

Const $JSON_DATA  = '{"x-ID.0":{"name":"Fox 2 KTVI","x-update-channel-icon":false,"x-update-channel-name":false,"x-description":""},"x-ID.1":{"name":"CBS 4 KMOV","x-name":"CBS 4 | HD","x-update-channel-icon":false,"x-update-channel-name":false,"x-description":""}}'

Const $JQ_FILTER  = 'walk( '                                                                   & _
                    '  if (.name? // ""| startswith("Fox 2") ) then '                          & _
                    '    (."x-update-channel-icon" = true | ."x-update-channel-name" = true) ' & _
                    '  else '                                                                  & _
                    '    . '                                                                   & _
                    '  end '                                                                   & _
                    ')'

;Initialize jq
_jqInit("C:\<path to jq executable>\jq-win64.exe") ;<== Modify as needed
If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "ERROR: Unable to initialize jq - @error = " & @error)

;Replace specified values
$sCmdOutput = _jqExec($JSON_DATA, $JQ_FILTER)

;Display results
ConsoleWrite("Before:" & @CRLF)
ConsoleWrite(_jqPrettyPrintJson($JSON_DATA) & @CRLF)
ConsoleWrite(@CRLF)
ConsoleWrite("After:" & @CRLF)
ConsoleWrite($sCmdOutput & @CRLF)

Console output

Before:
{
  "x-ID.0": {
    "name": "Fox 2 KTVI",
    "x-update-channel-icon": false,
    "x-update-channel-name": false,
    "x-description": ""
  },
  "x-ID.1": {
    "name": "CBS 4 KMOV",
    "x-name": "CBS 4 | HD",
    "x-update-channel-icon": false,
    "x-update-channel-name": false,
    "x-description": ""
  }
}

After:
{
  "x-ID.0": {
    "name": "Fox 2 KTVI",
    "x-update-channel-icon": true,
    "x-update-channel-name": true,
    "x-description": ""
  },
  "x-ID.1": {
    "name": "CBS 4 KMOV",
    "x-name": "CBS 4 | HD",
    "x-update-channel-icon": false,
    "x-update-channel-name": false,
    "x-description": ""
  }
}

 

Edited by TheXman
Link to post
Share on other sites
1 hour ago, TheXman said:

The only issue with your example is that the result will only be the selected keys' object values without their keys. 

Ah now i see the difference in our results. You're completely right - I simply did not look closely at my result.

Since this was the very first time I ever dealt with jq, I assumed anyway that improvements to my approach were needed.

Link to post
Share on other sites
21 minutes ago, AspirinJunkie said:

was the very first time I ever dealt with jq

For being the very first time dealing with jq. or even the first few times, that was a relatively complex filter that you came up with.  It was definitely on the right path to a different way to achieve the same result.  Nice job!  Like anything else, the more you do/use it, the easier it becomes.  :thumbsup:

Edited by TheXman
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
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...