Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Programmieren allgemein (https://www.delphipraxis.net/40-programmieren-allgemein/)
-   -   JSON mit Punkt im Namen (https://www.delphipraxis.net/212809-json-mit-punkt-im-namen.html)

Andreas Schilling 5. Apr 2023 10:41

JSON mit Punkt im Namen
 
Den Abruf eines JSON-Objekt bekomme ich hin. Sieht dann so aus
Delphi-Quellcode:
{
    "pagination": {
       
    },
    "data": [
        {
            "id": 158,
             ....
            "initialConfig": {
                "APN": "iot.1nce.net",
                ...
            },
            "properties": {
                "debug.monitor": {
                    "name": "debug.monitor",
                    "value": "...",
                    "updatedAt": "2023-01-31T09:23:15.611854289Z"
                },
                ....
                "platform.wmbus.receivedMeters": {
                    "name": "platform.wmbus.receivedMeters",
                    "value": [
                        "01280XXX",
                        "03780XXX",
                        ....
                    ],

Das Auslesen von ID funktioniert mit:

Delphi-Quellcode:
sID := JSONValue.GetValue<string>('data['+inttostr(i)+'].id');

Das Auslesen "initialConfig": { "APN": "iot.1nce.net", funktioniert auch mit

Delphi-Quellcode:
sAPN := JSONValue.GetValue<string>('data['+inttostr(i)+'].initialConfig.APN');

Aber wenn ein Punkt im Knotennamen ist "properties": { "debug.monitor": { "name" ... kommt eine Fehlermeldung "Wert'data[0].properties.debug.monitor.name' nicht gefunden" bei

Delphi-Quellcode:
sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+'].properties.debug.monitor.name');

Wie würde der Syntax bei dieser Bedingung lauten?

Gruß Andreas

himitsu 5. Apr 2023 11:05

AW: JSON mit Punkt im Namen
 
Vielleicht mit " oder ' oder \ escapen
Delphi-Quellcode:
sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+'].properties."debug.monitor".name');

sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+'].properties.''debug.monitor''.name');

sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+'].properties.debug\.monitor.name');
oder kann man eventuell auch \ bzw. / als Node-Separator benutzen?
Delphi-Quellcode:
sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+']\properties\debug.monitor\name');

sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+']\\properties\\debug.monitor\\name');

sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+']/properties/debug.monitor/name');

himitsu 5. Apr 2023 11:20

AW: JSON mit Punkt im Namen
 
:angle:

Delphi-Quellcode:
  /// <summary> Parses a JSON path with names and indexes.</summary>
  /// <remarks>
  ///  The syntax to write paths is similar to XPath but in a Json way.
  ///  The following XPath expression:
  ///    /entities/urls[0]/indices[1]
  ///  would look like
  ///    entities.urls[0].indices[1]  (dot notation)
  ///  or
  ///    entities["urls"][0]["indices"][1]  (bracket notation)
  ///
  ///  The dot (.) token is used to access the object elements:
  ///    ex: object.key
  ///
  ///  The bracket ([]) token is used to access array or object elements:
  ///    In array: cities[0]
  ///    In object: city["name"] or city['name']
  ///    In object: ["city"]["name"] or ['city']['name']
  ///
  ///  The quote (" or ') is used to introduce a literal when the element is being written in bracket notation:
  ///    ex:["first"]["second"] or ['first']['second']
  ///
  ///  To escape the quote in a literal use backslash (\): \"
  ///    ex: ["quotes(\").should.be.escaped"] or ['quotes(\').should.be.escaped']
  ///
  ///  Note: The backslash will only escape quotes within a literal. Bracket notation can be useful when
  ///  names can not be written in dot notation, like the objects keys with dot characters:
  ///    ex: object["key.with.dots"] or object['key.with.dots']
  ///
  /// </remarks>
  TJSONPathParser = record
Zitat:

Note: The backslash will only escape quotes within a literal. Bracket notation can be useful when
names can not be written in dot notation, like the objects keys with dot characters
:
ex: object["key.with.dots"] or object['key.with.dots']

Andreas Schilling 5. Apr 2023 11:57

AW: JSON mit Punkt im Namen
 
Das hier hat jetzt funktioniert

Delphi-Quellcode:
sProperties_3 := JSONValue.GetValue<string>('data['+inttostr(i)+']["properties"]["debug.monitor"]["name"]');

Danke für die Hinweise. Ein paar Sachen hatte ich schon vorher ausprobiert aber auf ["..."] wäre ich nicht gekommen.

Gruß Andreas

Andreas Schilling 6. Apr 2023 05:22

AW: JSON mit Punkt im Namen
 
Eigentlich müsste ich den Namen des Thema etwas anpassen, weil es geht zwar um den gleichen JSON-Abruf aber um den nächsten Schritt.

Delphi-Quellcode:
"platform.wmbus.receivedMeters": {
                    "name": "platform.wmbus.receivedMeters",
                    "value": [
                        "01280XXX",
                        "03780XXX",
                        ....
                    ],

Im letzten Teil des Ausschitt oben gibt es ein Unter-Array "value", aber nicht in der Form wie ich es in Beispielen gefunden habe mit
Delphi-Quellcode:
[{"name" : ..., "Bez": ...} { ... }]

sondern wie es oben zu sehen ist. Alle Varianten welche ich probiert habe bringen keinen Fehler sondern liefern nur nil zurück. Ich habe versucht jeden einzelnen "data"-Abschnitt in ein eigens Objekt zu packen was funktioniert und mit dem weiter gearbeitet. Aber solche Abfrgaen liefern nichts zurück

Delphi-Quellcode:
JsonArray2 := JsonObj2.GetValue('["properties"]["platform.wmbus.receivedMeters"]["value"]') as TJSONArray;


Gruß Andreas

Klaus01 6. Apr 2023 06:51

AW: JSON mit Punkt im Namen
 
Delphi-Quellcode:
const
  jsonString = '{ "properties": { ' +
               '  "platform.wmbus.receivedMeters": { '+
               '    "name": "platform.wmbus.receivedMeters", '+
               '    "value": [ '+
               '        "01280XXX", '+
               '        "03780XXX" '+
               '    ]}}}';

var
  jsonArray: TJsonArray;
  jsonObj: TJsonObject;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    jsonObj := TJSONObject.ParseJSONValue(jsonString) as TJSONObject;
    jsonArray := JsonObj.GetValue<TJsonArray>('["properties"]["platform.wmbus.receivedMeters"]["value"]');
    if jsonArray.Count > 0 then
      writeLn(jsonArray.Items[0].GetValue<String>);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
funktioniert tadellos.

Grüße
Klaus

Andreas Schilling 6. Apr 2023 07:28

AW: JSON mit Punkt im Namen
 
Danke Klaus, funktioniert. Hast gleich meine noch garnicht gestellte Frage beantwortet wie man aus so einem Array dann den Wert ausliest.

Delphi-Quellcode:
sSerNr := jsonArray2.Items[k].GetValue<String>;

Gruß Andreas

himitsu 6. Apr 2023 09:16

AW: JSON mit Punkt im Namen
 
Das geht ebenfalls, wie du es ja schon benutzt hatttest, also
Delphi-Quellcode:
GetItem('data[0]')
, nur
Delphi-Quellcode:
Nummer
ohne " um den
Delphi-Quellcode:
"Namen"
.

Beachten solltest du aber, dass "data" ein Array ist, worin (mindestens) im ersten Wert ein Object liegt.
Delphi-Quellcode:
"data" : [ {
vs. Data direkt als Object
Delphi-Quellcode:
"data" : {
.
Das Objekt ist also SubItem/-Node von data[0], nicht nur von data,

Bbommel 6. Apr 2023 09:25

AW: JSON mit Punkt im Namen
 
Zitat:

Zitat von Andreas Schilling (Beitrag 1520717)
Im letzten Teil des Ausschitt oben gibt es ein Unter-Array "value", aber nicht in der Form wie ich es in Beispielen gefunden habe mit
Delphi-Quellcode:
[{"name" : ..., "Bez": ...} { ... }]

Kurzer Klugscheißer-Hinweis, um zukünftige Missverständnisse zu vermeiden: das, was du da beschreibst als das, was du in den Beispielen gefunden hast, ist kein Array, sodern ein JSON-Objekt. Ein Objekt besteht immer aus einem Paar Eigenschaftsname+Wert. Der Wert kann dabei ein String, eine Nummer, ein Boolen, selbst wiederum ein Objekt oder eben ein echtes Array sein. In deinem Beispiel ist erst das, was du unter "value" hast, tatsächlich ein Array, erkennbar am [ und ].

Hilft dann wahrscheinlich auch, die Umsetzung der JSON-Bibliothek in Delphi etwas besser nachvollziehen zu können. :-)


Alle Zeitangaben in WEZ +1. Es ist jetzt 03:46 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz