I am trying to create a map from a result of a SOQL query, this map contains the name of the fields as keys and the values of the query as values for example:

List accounts = [SELECT Name, Email FROM Account];

and the map Map has this structure:

key         value
name        123 
email       test@test.co.uk

any ideas please ?

  • 1
    Why do you need it to be a map?
    – Adrian Larson
    Mar 7, 2016 at 15:33

2 Answers 2


An SObject record has a very map-like structure by default.

Account record = [SELECT Name, Email FROM Account LIMIT 1];

It even supports put:

record.put('Email', 'newemailaddress@example.com');

However, if you absolutely must have a map for some reason, you can use serialization (a CPU intensive process) as follows:

String representation = JSON.serialize(record);
Map<String, Object> dataMap = (Map<String, Object>)JSON.deserializeUntyped(representation);

SObject.getPopulatedFieldsAsMap() does the job for you. From Summer '16 this feature is available to convert SObject class to map.


  • 1
    I wouldn't necessarily say that it converts the SObject into a Map<String, Object>, as the original SObject remains intact. It certainly takes a given SObject and generates/returns a Map<String, Object> though. I might just be nit-picking.
    – Derek F
    Apr 26, 2019 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.