Skip to content

Conversation

@rgoldberg
Copy link
Contributor

@rgoldberg rgoldberg commented Oct 21, 2025

Provide subscripts for JSON.Object to return the first key-value pair whose key matches a given key.

Resolve #93

…ir whose key matches a given key.

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
@tayloraswift
Copy link
Owner

i don’t think this is the right layer for this API. i believe there is a type JSON.ObjectDecoder which is designed for this purpose, and supports O(1), as opposed to O(n) access

@rgoldberg
Copy link
Contributor Author

I parse JSON provided by a third-party that doesn't provide a spec.

I map various keys from the original JSON to new key names, and I sort the JSON based on the new key names.

I've never seen duplicate keys in the provided JSON, but, if duplicate keys exist, I want to map all of them & retain all duplicate keys.

I use JSONDecodable instead of JSONObjectDecodable because the latter uses JSON.ObjectDecoder, which seems to not support duplicate keys (please let me know if I'm wrong).

My internal processing must extract a few values from the input JSON.

The subscripts in this PR extract the first value listed in the JSON for a given key.

Does swift-json provide any better way to do what I need?

Here's an example of code that uses the subscripts from this PR:

extension SearchResult: JSONDecodable {
	fileprivate init(json: JSON.Node) throws {
		guard case let .object(object) = json else {
			throw MASError.jsonParsing(input: String(describing: json))
		}

		adamID = try object["trackId"]?.decode() ?? 0
		appStorePageURL = try object["trackViewUrl"]?.decode() ?? ""
		sellerURL = try object["sellerUrl"]?.decode()

		self.json = String(describing: json.mappingKeys)
	}
}

private extension JSON.Node {
	var mappingKeys: Self {
		// map keys & sort them
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Provide subscripts for JSON.Object to return the first key-value pair whose key matches a given key

2 participants