Recent

Author Topic: [Solved] Adding String to Json Data  (Read 446 times)

nikel

  • Sr. Member
  • ****
  • Posts: 252
[Solved] Adding String to Json Data
« on: April 17, 2025, 01:18:28 am »
Hello, I'm trying to insert strings to my json data. JObject.Objects['3'].Add('album', 'Album 3'); line is giving me error: Invalid typcast. Here's my code.

Code: Pascal  [Select][+][-]
  1. try
  2. begin  // this is only a minimal sampling of what can be done with this API
  3.   // create from string
  4.   JData:=GetJSON('{    "1": {' +
  5.         '"album": "Test Album 1",' +
  6.         '"artist": "Test Singer 1",' +
  7.         '"bpm": 120,' +
  8.         '"duration": 180,' +
  9.         '"is_enabled": true,' +
  10.         '"key": "A",' +
  11.         '"num_played": 0,' +
  12.         '"path": "/home/user/Desktop/akustik/cem_adrian___sen_benim_sarkilarimsin.mp3",' +
  13.         '"played_at": "01.01.2000",' +
  14.         '"stars": 5,' +
  15.         '"title": "Test \u015eark\u0131s\u0131",' +
  16.         '"year": 1999' +
  17.   '},' +
  18.   '"2": {' +
  19.         '"album": "Test Album 2",' +
  20.         '"artist": "Test Singer 2",' +
  21.         '"bpm": 120,' +
  22.         '"duration": 180,' +
  23.         '"is_enabled": true,' +
  24.         '"key": "A",' +
  25.         '"num_played": 0,' +
  26.         '"path": "/home/user/Desktop/akustik/cem_adrian___sen_benim_sarkilarimsin.mp3",' +
  27.         '"played_at": "01.01.2000",' +
  28.         '"stars": 5,' +
  29.         '"title": "Test \u015eark\u0131s\u0131",' +
  30.         '"year": 1999' +
  31.   '}}');
  32.  
  33.   // output as a flat string
  34.   StrPtr^:=JData.AsJSON;
  35.  
  36.   // output as nicely formatted JSON
  37.   StrPtr^:=JData.FormatJSON;
  38.  
  39.   // cast as TJSONObject to make access easier
  40.   JObject:=JData as TJSONObject;
  41.  
  42.   // retrieve value of Fld1
  43.   // StrPtr^:=JObject.Get('title');
  44.  
  45.   // change value of Fld2
  46.   JObject.Objects['2'].Strings['album']:='Album 2';
  47.  
  48.   // retrieve the second color
  49.   // StrPtr^:=JData.FindPath('Colors[1]').AsString;
  50.  
  51.   // add a new element
  52.   JObject.Add('3');
  53.  
  54.   JObject.Objects['3'].Add('album', 'Album 3');

How can I add some strings to Json?
« Last Edit: April 17, 2025, 03:04:42 am by nikel »

dseligo

  • Hero Member
  • *****
  • Posts: 1507
Re: Adding String to Json Data
« Reply #1 on: April 17, 2025, 02:58:11 am »
Change line 52 to:
Code: Pascal  [Select][+][-]
  1.       // add a new element
  2.       JObject.Add('3', TJSONObject.Create); // change this line!
  3.      
  4.       JObject.Objects['3'].Add('album', 'Album 3');

nikel

  • Sr. Member
  • ****
  • Posts: 252
Re: Adding String to Json Data
« Reply #2 on: April 17, 2025, 03:04:16 am »
That worked fine. Thank you.

 

TinyPortal © 2005-2018