• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Modify JSON in Swift
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Modify JSON in Swift


  • Subject: Modify JSON in Swift
  • From: Rick Mann <email@hidden>
  • Date: Fri, 06 Nov 2015 22:54:32 -0800

I'm trying to do this, but I can't modify the JSON structure.


-----------------------
import Foundation

let s = "{ \"images\" : [ { \"thumb\" : \"url1\", \"width\" : 10 }, { \"thumb\" : \"url2\", \"width\" : 20 } ] }"
let data = (s as NSString).dataUsingEncoding(NSUTF8StringEncoding)!

do
{
	if var json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
	{
		print("JSON: \(json)")
		if var images = json["images"] as? [[String:AnyObject]]
		{
			for var image in images
			{
				if let thumbURL = image["thumb"]
				{
					image["thumb"] = "FOOBAR: \(thumbURL)"
					print("new: \(image["thumb"])")
				}
			}

			let newData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(rawValue: 0))
			let s2 = NSString(data: newData, encoding: NSUTF8StringEncoding)
			print(s2)
		}
	}
}

catch let e as NSError
{
	print("Error parsing model.json: \(e)")
}
-----------------------
JSON: ["images": (
        {
        thumb = url1;
        width = 10;
    },
        {
        thumb = url2;
        width = 20;
    }
)]
new: Optional(FOOBAR: url1)
new: Optional(FOOBAR: url2)
Optional({"images":[{"thumb":"url1","width":10},{"thumb":"url2","width":20}]})
-----------------------

But it seems the way I drill down into the initial json dictionary gives me copies, or otherwise prevents me from modifying the dictionary like this.

Any suggestions on what I can do? I really don't want to have to walk and rebuild the JSON myself.

--
Rick Mann
email@hidden



_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


  • Follow-Ups:
    • Re: Modify JSON in Swift
      • From: Roland King <email@hidden>
    • Re: Modify JSON in Swift
      • From: Quincey Morris <email@hidden>
  • Prev by Date: Re: debugging AutoLayout exception with no build errors
  • Next by Date: Re: Modify JSON in Swift
  • Previous by thread: Re: Do playgrounds work at all in 7.1?
  • Next by thread: Re: Modify JSON in Swift
  • Index(es):
    • Date
    • Thread