Page 1 of 1

Compose a JSON member as a string?

Posted: Wed Aug 21, 2024 5:38 am
by Seymour Clufley
I need to go through JSON records and, in each case, find a particular member and then extract that (and all its subs) as a string. I can find it easily enough, but extracting it is another matter. Is there any easy way to do this?

Code: Select all

c34.s = Chr(34)
jsonString.s = "{"+c34+"blob"+c34+":{"+c34+"mimeType"+c34+":"+c34+"image/jpeg"+c34+","+c34+"$type"+c34+":"+c34+"blob"+c34+","+c34+"size"+c34+":11689,"+c34+"ref"+c34+":{"+c34+"$link"+c34+":"+c34+"bafkreih44nkqvldurfdvtnctr3m7a3wmn7ayv2vku3oyhdslzdj3pidarm"+c34+"}}}"
j = ParseJSON(#PB_Any,jsonString)

If j
  ObjectValue = JSONValue(j)
  If ExamineJSONMembers(ObjectValue)
    While NextJSONMember(ObjectValue)
      Select JSONMemberKey(ObjectValue)
        Case "blob"
          value = JSONMemberValue(ObjectValue)
          If ExamineJSONMembers(value)
            While NextJSONMember(value)
              If JSONMemberKey(value) = "ref"
                value2 = JSONMemberValue(value)
                t.s = ComposeJSON(value2)
                Break 2
              EndIf
            Wend
          EndIf
      EndSelect
    Wend
  EndIf
  FreeJSON(j)
EndIf

Re: Compose a JSON member as a string?

Posted: Wed Aug 21, 2024 7:11 am
by Kiffi
Seymour Clufley wrote: Wed Aug 21, 2024 5:38 amIs there any easy way to do this?

Code: Select all

EnableExplicit

Structure sRef
  link.s
EndStructure

Structure sBlob
  mimeType.s
  type.s
  size.i
  ref.sRef
EndStructure

Structure sJson
  blob.sBlob
EndStructure

Define c34.s = Chr(34)
Define jsonString.s = "{"+c34+"blob"+c34+":{"+c34+"mimeType"+c34+":"+c34+"image/jpeg"+c34+","+c34+"$type"+c34+":"+c34+"blob"+c34+","+c34+"size"+c34+":11689,"+c34+"ref"+c34+":{"+c34+"$link"+c34+":"+c34+"bafkreih44nkqvldurfdvtnctr3m7a3wmn7ayv2vku3oyhdslzdj3pidarm"+c34+"}}}"

jsonString = ReplaceString(jsonString,"$type", "type")
jsonString = ReplaceString(jsonString,"$link", "link")

Define json.sJson

If ParseJSON(0, jsonString)
  
  ExtractJSONStructure(JSONValue(0), @json, sJson)
  FreeJSON(0)
  
  Debug json\blob\mimeType
  Debug json\blob\type
  Debug json\blob\size
  Debug json\blob\ref\link
  
Else
  
  Debug JSONErrorMessage()
  
EndIf

Re: Compose a JSON member as a string?

Posted: Wed Aug 21, 2024 7:25 am
by infratec
Do you know the JSON structure?
Is it always the same?

Then use ExtractJSONStructure()

Re: Compose a JSON member as a string?

Posted: Wed Aug 21, 2024 9:31 am
by Seymour Clufley
Yes, it's always the same JSON structure so I can use ExtractJSONStructure(), but I hoped there would be a simpler and more elegant way of doing this. Thanks for your replies.