How do I parse empty dictionary JSON in Swift? - json

I am parsing JSON using swift. I came to a dictionary which returns empty. How would I go about parsing this into a custom object?
** I am looking at Image**
},
"name": "Al bake",
"image": {},
"website": "",
"category": {
"id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84",
"name": "Test Category",
"slug": "test-category",
"is_active": true
},

If you need the value for image, which should be a dictionary (empty or containing keys & values), you need to know the type that contains it.
For instance, let's assume that the following code is contained in a dictionary:
"name": "Al bake",
"image": {},
"website": "",
"category": {
"id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84",
"name": "Test Category",
"slug": "test-category",
"is_active": true
You would do something like this:
if let image = dictionary["image"] as? Dictionary<String, Any> {
print(image.description)
} else {
print("Image does not contain a value")
}

Related

Parse unstructured json in golang

Is there any solution to parse an unstructured json(text) data?
below is a sample response of a web requst that i want to parse and access data (the inner list)
res,err := http.Get("url_of_server")
[[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
],
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
]
what i want to get is:
[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
]
in python it is possible by easily using res.json()[0]
I have tried using json.Unmarshal() to a map and also struct but does not work,
i don't know how to get rid of this part of response:
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
Declare a type for the items:
type Item struct {
ID string `json:"id"`
Text string `json:"text"`
User struct {
UserID string `json:"user_id"`
Username string `json:"username"`
} `json:"user"`
CreatedAtUtc time.Time `json:"created_at_utc"`
Status string `json:"status"`
}
Declare a slice of the items:
var items []Item
Declare a slice representing the entire JSON thing. The first element is the items.
var v = []any{&items}
Unmarshal to v. The items slice will have the values that you are looking for. The second and third elements of v will contain the values you want to ignore.
err := json.Unmarshal(data, &v)
Run the code in the GoLang PlayGround.
Go's standard JSON library is not as flexible as others when it comes to dealing with unexpected or uncontrolled input.
A great alternative is tidwall's gjson.
Example code with gjson:
package main
import (
"fmt"
"github.com/tidwall/gjson"
)
const textInput = `[[
{
"id": "1",
"text": "sample text",
"user": {
"user_id": "1",
"username": "user1"
},
"created_at_utc": "2022-12-20T16:38:06+00:00",
"status": "Active"
},
{
"id": "2",
"text": "sample text",
"user": {
"user_id": "2",
"username": "user2"
},
"created_at_utc": "2022-12-01T10:15:00+00:00",
"status": "Active"
}
],
"{"code": "hsdvnkvuahudvhafdlfv",
"is_updated": true}",
null
]`
func main() {
jsonBody := gjson.Parse(textInput)
fmt.Println(jsonBody.Get("0"))
}

How to get JSON data from attributes that start with # or # in Typescript

I am working with a specific API that returns a JSON that looks like the below sample.
I want to get both values that contain the #text and #attr but I get error messages in typescript when I try to get the values.
try using,
album[0]["#attr"]
album[0]["artist"]["#text"]
Hey for JSON you can use get details by its attribute name in it and it's the same for all-weather it starts with # or # it will be the same.
See below code to get the value of your specified key:
Sample JSON:
{
"weeklyalbumchart": {
"album": [
{
"artist": {
"mbid": "data",
"#text": "Flying Lotus"
},
"mbid": "data",
"url": "",
"name": "",
"#attr": {
"rank": "1"
},
"playcount": "21"
},
{
"artist": {
"mbid": "data",
"#text": "Flying Lotus"
},
"mbid": "data",
"url": "",
"name": "",
"#attr": {
"rank": "1"
},
"playcount": "21"
}
]
}
}
Read JSON:
#attr ===> json["weeklyalbumchart"]["album"][0]["#attr"]
#text ===> json["weeklyalbumchart"]["album"][0]["artist"]["#text"]
Hope this will help you to understand it.

unencode json in Zapier

I'm trying to make a Zapier zap to get a JSON from Olark.
This is the sample JSON Olark sends...
{
"kind": "Conversation",
"id": "EV695BI2930A6XMO32886MPT899443414",
"tags": ["olark", "customer"],
"items": [{
"kind": "MessageToVisitor",
"nickname": "John",
"timestamp": "1307116657.1",
"body": "Hi there. Need any help?",
"operatorId": "1234"
},
{
"kind": "MessageToOperator",
"nickname": "Bob",
"timestamp": "1307116661.25",
"body": "Yes, please help me with billing."
}],
"visitor": {
"kind": "Visitor",
"id": "9QRF9YWM5XW3ZSU7P9CGWRU89944341",
"fullName": "Bob Doe",
"emailAddress": "bob#example.com",
"phoneNumber": "(555) 555-5555",
"city": "Palo Alto",
"region": "CA",
"country": "United State",
"countryCode": "US",
"organization": "Widgets Inc.",
"ip": "123.4.56.78",
"browser": "Chrome 12.1",
"operatingSystem": "Windows",
"conversationBeginPage": "http://www.example.com/path",
"customFields": {
"myInternalCustomerId": "12341234",
"favoriteColor": "blue"
},
"chat_feedback": {
"comments": "Very helpful, thanks",
"friendliness": 5,
"knowledge": 5,
"overall_chat": 5,
"responsiveness": 5
}
},
"operators": {
"1234": {
"kind": "Operator",
"id": "1234",
"username": "jdoe",
"nickname": "John",
"emailAddress": "john#example.com"
}
},
"groups": [{
"name": "My Sales Group",
"id": "0123456789abcdef",
"kind": "Group"
}]
}
I can get what I want -- the email -- like this...
var obj = {};
var data = {};
data = JSON.parse(inputData.data);
obj.value = data.visitor["emailAddress"];
return obj;
However, the live data that comes from Olark is an encoded version of the JSON. It looks like this...
raw_body
data=%7B%22kind%22%3A+%22Conversation%22%2C+%22id%22%3A+%224pkhSGlkBYHz0gw83L6TF0UBa6rA39Bo%22%2C+%22manuallySubmitted%22%3A+false%2C+%22items%22%3A+%5B%7B%22kind%22%3A+%22MessageToOperator%22%2C+%22nickname%22%3A+%22juliachevron%40gmail.com%22%2C+%22timestamp%22%3A+%221588965389.388434%22%2C+%22body%22%3A+%22Hi.+I+have+a+stimulator+and+it+is+no+longer+working+at+the+higher+levels%22%2C+%22visitor_nickname%22%3A+%22juliachevron%40gmail.com%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965397.901964%22%2C+%22body%22%3A+%22Hi+there%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965408.398821%22%2C+%22body%22%3A+%22Can+you+explain+more%3F%22%7D%2C+%7B%22kind%22%3A+%22MessageToOperator%22%2C+%22nickname%22%3A+%22juliachevron%40gmail.com%22%2C+%22timestamp%22%3A+%221588965445.279921%22%2C+%22body%22%3A+%22it+is+only+flashing+up+to+the+2+and+sometimes+3%22%2C+%22visitor_nickname%22%3A+%22juliachevron%40gmail.com%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965482.985280%22%2C+%22body%22%3A+%22Try+our+%5C%22oreo%5C%22+troubleshooting+test+from+page+12+of+the+User+Guide%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965488.741729%22%2C+%22body%22%3A+%22It+involves+you+pressing+the+wet+sponges+into+each+other+as+you+turn+the+device+to+the+max+setting%22%7D%2C+%7B%22kind%22%3A+%22MessageToOperator%22%2C+%22nickname%22%3A+%22juliachevron%40gmail.com%22%2C+%22timestamp%22%3A+%221588965539.836595%22%2C+%22body%22%3A+%22thank+you%21%22%2C+%22visitor_nickname%22%3A+%22juliachevron%40gmail.com%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965583.359044%22%2C+%22body%22%3A+%22This+test+is+to+make+sure+the+device+is+functioning+correctly%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965619.075057%22%2C+%22body%22%3A+%22If+you+are+not+getting+to+the+higher+levels+when+the+sponges+are+on+your+temples%2C+it+may+mean+that+you+need+to+use+more+water%2C+tighten+the+headband+a+little+more%2C+or+that+you+need+to+replace+the+sponges%22%7D%2C+%7B%22kind%22%3A+%22MessageToOperator%22%2C+%22nickname%22%3A+%22juliachevron%40gmail.com%22%2C+%22timestamp%22%3A+%221588965698.050212%22%2C+%22body%22%3A+%22it+worked.+thanks%22%2C+%22visitor_nickname%22%3A+%22juliachevron%40gmail.com%22%7D%2C+%7B%22kind%22%3A+%22MessageToVisitor%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22operatorId%22%3A+%22663710%22%2C+%22timestamp%22%3A+%221588965702.713077%22%2C+%22body%22%3A+%22You%27re+very+welcome.%22%7D%5D%2C+%22tags%22%3A+%5B%5D%2C+%22visitor%22%3A+%7B%22kind%22%3A+%22Visitor%22%2C+%22id%22%3A+%22YN7k5dd6nGH52Lvd3L6TF0VBb03B3roI%22%2C+%22fullName%22%3A+%22juliachevron%40gmail.com%22%2C+%22emailAddress%22%3A+%22juliachevron%40gmail.com%22%2C+%22ip%22%3A+%22%22%2C+%22city%22%3A+%22Oak+Park%22%2C+%22region%22%3A+%22IL%22%2C+%22country%22%3A+%22United+States%22%2C+%22countryCode%22%3A+%22US%22%2C+%22organization%22%3A+%22Comcast+Cable%22%2C+%22browser%22%3A+%22Chrome+80.0.3987.149%22%2C+%22operatingSystem%22%3A+%22Macintosh%22%2C+%22referrer%22%3A+%22https%3A%2F%2Fwww.google.com%2F%22%2C+%22conversationBeginPage%22%3A+%22https%3A%2F%2Fwww.fisherwallace.com%2F%22%2C+%22chat_feedback%22%3A+%7B%7D%7D%2C+%22operators%22%3A+%7B%22663710%22%3A+%7B%22kind%22%3A+%22Operator%22%2C+%22id%22%3A+%22663710%22%2C+%22nickname%22%3A+%22Christian%22%2C+%22emailAddress%22%3A+%22christian%40fisherwallace.com%22%2C+%22username%22%3A+%22fisherwallace%22%7D%7D%7D
And I get "SyntaxError: Unexpected token d in JSON at position 0" when I try to parse it with the code that works on the sample JSON.
Is there a way in Zapier to unencode the JSON?
There sure is! What you're seeing is percent encoding. Node.js can decode that, but to get valid json, you'll also need to replace the + characters with spaces.
Try this:
const inputWithReplacedSpaces = inputData.data.replace(/\+/g, '%20') // '%20' is a space
const jsonStr = decodeURIComponent(inputWithReplacedSpaces)
const data = JSON.parse(jsonStr)
return { email: data.visitor.emailAddress }
There were two issues. See screenshot.
I needed to set the Import Data to "data" in the Custom Run Javascript step. And also remove the "data=" from the string at the beginning of the Raw Body.

Using a template variable that contains a JSON object with Postman Collection Runner

I am attempting to use the Postman collection runner to post several objects to an API from a JSON file structured something like this:
[
{
"id": "170",
"body": {
"name": "prod1",
"category": "category1"
},
"anotherProperty": "xyz"
},
{
"id": "171",
"body": {
"name": "prod3",
"category": "category1"
},
"anotherProperty": "dfg"
},
{
"id": "172",
"body": {
"name": "prod3",
"category": "category1"
},
"anotherProperty": "abc"
}
]
My problem seems to be with the body since it is an object:
Here is what I have in the Body > raw application/json of the request that my collection is using:
{
"$id": "{{id}}",
"body": {{body}},
"anotherProperty": "{{anotherProperty}}"
}
When viewing what it is plugging in it looks like:
{
"id": "170",
"body": {[object Object]}, // instead of the actual object
"anotherProperty": "xyz"
}
I needed to add the following to the Pre-request script:
let properties = pm.iterationData.get('properties');
pm.variables.set('properties', JSON.stringify(properties));
let body = pm.iterationData.get('body');
pm.variables.set('body', JSON.stringify(body));
And the raw JSON is plugged in with no problem!

How to format json output in pyspark?

I am having a trouble to preserve the order of my json and pretty printing it in pyspark.
Below is sample code:
json_out = sqlContext.jsonRDD(sc.parallelize([json.dumps(info)]))
# here info is my ordered dictionary
json_out.toJSON().saveAsTextFile("file:///home//XXX//samplejson")
One more thing is that I want my output as single file and not as partitioned datasets.
Could anyone help in pretty printing and preserving the order of output json in my case?
info sample:
Note:TypeA,TypeB etc is a list meaning there can be more than one product in TypeA or TypeB.
{
"score": {
"right": ,
"wrong":
},
"articles": {
"TypeA": [{
"ID": 333,
"Name": "",
"S1": "",
"S2": "",
"S3": "",
"S4": ""
}],
"TypeB": [{
"ID": 123,
"Name": "",
"T1": "",
"T2": "",
"T3": "",
"T4": "",
"T5": "",
"T6": ""
}]
}
}
( I have tried using json.dumps(info,indent=2),but of no use.